Passing PHP variables to Javascript
Moderator: General Moderators
Passing PHP variables to Javascript
Can anyone tell me the best way to pass a PHP array into a Javascript array? It just crossed my mind just now. 
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Passing PHP variables to Javascript
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)
Re: Passing PHP variables to Javascript
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?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.
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
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: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?
Code: Select all
echo "js_arr.push('$element');\n";Re: Passing PHP variables to Javascript
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:
[/quote]
Hey, it worked. Thanks!
Code: Select all
echo "js_arr.push('$element');\n";Hey, it worked. Thanks!