Page 1 of 1

Passing PHP variables to Javascript

Posted: Fri Oct 16, 2009 12:53 am
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:

Re: Passing PHP variables to Javascript

Posted: Fri Oct 16, 2009 1:06 am
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.

Re: Passing PHP variables to Javascript

Posted: Fri Oct 16, 2009 1:27 am
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);
 

Re: Passing PHP variables to Javascript

Posted: Fri Oct 16, 2009 1:39 am
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";

Re: Passing PHP variables to Javascript

Posted: Fri Oct 16, 2009 3:21 am
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!