PHP in Javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
hussy
Forum Newbie
Posts: 2
Joined: Sat Jul 09, 2011 3:20 am

PHP in Javascript

Post 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.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: PHP in Javascript

Post 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)
hussy
Forum Newbie
Posts: 2
Joined: Sat Jul 09, 2011 3:20 am

Re: PHP in Javascript

Post 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?
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: PHP in Javascript

Post 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.
Post Reply