Passing PHP variables to Javascript

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
enchance
Forum Commoner
Posts: 34
Joined: Sat Sep 15, 2007 12:10 pm

Passing PHP variables to Javascript

Post by enchance »

Can anyone tell me the best way to pass a PHP array into a Javascript array? It just crossed my mind just now. :drunk:
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Passing PHP variables to Javascript

Post by Christopher »

PHP is used to generate HTML or Javascript, so you can just generate a Javascript array as part of the HTML page source that is sent to the browser. For Ajax style communication you can pass JSON or XML to Javascript and it can convert it to objects/arrays.
(#10850)
enchance
Forum Commoner
Posts: 34
Joined: Sat Sep 15, 2007 12:10 pm

Re: Passing PHP variables to Javascript

Post by enchance »

arborint wrote:PHP is used to generate HTML or Javascript, so you can just generate a Javascript array as part of the HTML page source that is sent to the browser. For Ajax style communication you can pass JSON or XML to Javascript and it can convert it to objects/arrays.
I'm not too familiar wit JSON Or XML but here's what I have so far but it doesn't work though. What's wrong with it? :roll:

Code: Select all

 
var js_arr = [];
<?php
$tempo_arr = array('list', 'of', 'elements');
foreach($tempo_arr as $element)
{
    echo "js_arr.push($element);\n";
}
?>
alert(js_arr);
 
pa28
Forum Newbie
Posts: 7
Joined: Mon Oct 05, 2009 9:26 pm

Re: Passing PHP variables to Javascript

Post by pa28 »

enchance wrote: I'm not too familiar wit JSON Or XML but here's what I have so far but it doesn't work though. What's wrong with it? :roll:
You need to quote the $element within your echo statement, otherwise JavaScript will think you're trying to add variables called 'list', 'of', and 'elements' to the array - and those variables don't exist:

Code: Select all

echo "js_arr.push('$element');\n";
enchance
Forum Commoner
Posts: 34
Joined: Sat Sep 15, 2007 12:10 pm

Re: Passing PHP variables to Javascript

Post by enchance »

You need to quote the $element within your echo statement, otherwise JavaScript will think you're trying to add variables called 'list', 'of', and 'elements' to the array - and those variables don't exist:

Code: Select all

echo "js_arr.push('$element');\n";
[/quote]

Hey, it worked. Thanks!
Post Reply