Page 1 of 1
PHP in Javascript
Posted: Sat Jul 09, 2011 3:26 am
by hussy
Hi there, is it wrong to do this...
<script type="text/javascript">
var id = <?php echo ($est) ?>; //this works fine, just not sure if it is good practice
alert(id);
</script>
Thanks in advance.
Re: PHP in Javascript
Posted: Sat Jul 09, 2011 6:56 am
by Apollo
Sure, why not. Javascript is simply part of your html, thus part of the output you generate from php.
Just keep in mind what runs where: php runs server side, and once the html (and possibly any javascript therein) is generated, it's being sent to the visitor's browser which then displays/runs it.
(you seem to have this straight, just mentioning it for people who may not)
Re: PHP in Javascript
Posted: Sun Jul 10, 2011 6:58 pm
by hussy
Thanks Apollo.
Are there any methods in PHP that can set the variable for use in javascript? Haven't tried it yet but I am assuming you can do a window/global variable. And if so is it any better than the way I did it in my original post?
Re: PHP in Javascript
Posted: Mon Jul 18, 2011 3:59 am
by Apollo
Well you could do
Code: Select all
<?php
$fruit = 'apple';
print("<script type='text/javascript'> var food='$fruit'; alert('menu of the day: '+food); </script>");
?>
The javascript
food variable now becomes the content of php's
$fruit variable.