Page 1 of 1
How can i insert php variable into javascript?
Posted: Sun Sep 21, 2014 11:12 am
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?
Re: How can i insert php variable into javascript?
Posted: Sun Sep 21, 2014 11:22 am
by vitinho444
I've asked this a long time ago, and I still don't know the answer
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.
Re: How can i insert php variable into javascript?
Posted: Sun Sep 21, 2014 1:00 pm
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>";
Re: How can i insert php variable into javascript?
Posted: Sun Sep 21, 2014 4:44 pm
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
Re: How can i insert php variable into javascript?
Posted: Tue Sep 23, 2014 11:46 pm
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.