Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to pass a json_encoded array from php (which reads mysql and produces an array) to javascipt so I can use the array as input to a java chart. The problem is that the array is fine in the php part (I run nthe php separately and use echo and print_r to check the contents and is all fine). Immediately after the php code I have javascript which always gets an empty array.
I used several different attempts, all recommended as solutions on various forums and none of them work. Putting quotes around the call to get the array just echoes the command to my variable, anything else just returns empty.
My code (snip) looks like...

// Using json_encode puts the data into an array format that we can use in a javascript
$amJSONArray = json_encode($amData);

// Echo is for debugging only.
// echo $amJSONArray;

var chartData = "<?php print($amJSONArray); ?>";  // This just returns the literal in the speech marks
var chartData = '<?php print($amJSONArray); ?>';  // This also returns the literal in the speech marks
var chartData = <?php echo $amJSONArray ?>;       // This returns empty
var chartData = (<?php echo $amJSONArray ?>);     // This returns empty
alert(chartData);                                                                   // Returns empty - just showing the contents of the array if I do the json_encode within the php part
alert(<?php echo $amJSONArray ?>);                              // Returns empty - just showing the contents of the arra if I do the json_encode during the array fetch
Updated 22-Apr-13 10:01am
Prasad Khandekar 22-Apr-13 16:07pm    
Please have a look at this doc (

if you want to achieve this function,you need to use ajax.
your php side(a.php)
	$amJSONArray = json_encode($amData);
	echo $amJSONArray;

your js side(b.html)
<script src=""></script>
<script type="text/javascript">

try this,you will get the array from php side
Share this answer
If PHP is returning JSON, this should work

i = eval("(" + amJSONArray + ")");
Share this answer
enhzflep 23-Apr-13 13:20pm    
Yup, JSON.parse is a better option though - avoids so much of the horror that eval can unleash.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900