How can i insert php variable into javascript?

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
User avatar
kibo95
Posts: 35
Joined: Wed Jul 16, 2014 6:59 am

How can i insert php variable into javascript?

Post by kibo95 »

Hi
I have variable,that i've got from database
$example=$playerinfo3 ['level'];

Now i need to use this $example variable in javascript,how could i do that?
User avatar
vitinho444
Posts: 2825
Joined: Mon Mar 21, 2011 4:54 pm

Re: How can i insert php variable into javascript?

Post by vitinho444 »

I've asked this a long time ago, and I still don't know the answer :D

What I think it's best to do is to store it in a hidden html element like

Code: Select all

echo '<p id="var" style="display: none:">' . $example . '</p>';
Then just use javascript getElementById("var").innerHtml; and it will get the value of the variable.
Not the best solution, but might just work.
My Company Website: http://www.oryzhon.com

Skype: vpegas1234
User avatar
KyleMassacre
Posts: 573
Joined: Wed Nov 27, 2013 12:42 pm

Re: How can i insert php variable into javascript?

Post by KyleMassacre »

You can do:
JavaScript

Code: Select all

function myFunction(p1) {
    alert(p1 * 30);
}
PHP

Code: Select all

$var = 10;
echo "<button onclick='myFunction({$var});'>Click Me!</button>";
User avatar
kibo95
Posts: 35
Joined: Wed Jul 16, 2014 6:59 am

Re: How can i insert php variable into javascript?

Post by kibo95 »

can this second one be done withouth button,i need like 300 variables to be converted in javascript

Edit:
actually i think i found solution

Code: Select all

<?php

$var=15; //of course this is simplified as much as it can be
?>
<script type="text/javascript">
  var works= '<?php echo $var; ?>'
  document.write(works)
</script>
this works for me
User avatar
Jackolantern
Posts: 10893
Joined: Wed Jul 01, 2009 11:00 pm

Re: How can i insert php variable into javascript?

Post by Jackolantern »

Yep, you can do just about anything this way. Remember that PHP executes on the server where the webpage, including any Javascript, is generated and then sent to the user, at which point the Javascript is executed. Since they are executed at completely different times in completely different place, you can simply use PHP to write the Javascript you are sending to the client.
The indelible lord of tl;dr
Post Reply

Return to “Beginner Help and Support”