Click here to Skip to main content
15,891,873 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...

HTML
// 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
Posted
Updated 22-Apr-13 10:01am
v3
Comments
Prasad Khandekar 22-Apr-13 16:07pm    
Please have a look at this doc (http://php.net/manual/en/function.json-encode.php).

Hi,
if you want to achieve this function,you need to use ajax.
your php side(a.php)
PHP
	$amData=array(1,2,3,4);
	$amJSONArray = json_encode($amData);
	echo $amJSONArray;
?>

your js side(b.html)
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
	$(function(){
	      $.getJSON("a.php",function(result){
		  $.each(result,function(i,j){
			alert(j);//1,2,3,4
		  });
	      });
	})
</script>

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

JavaScript
<script>
.
.
.
i = eval("(" + amJSONArray + ")");
.
.
.
</script>
 
Share this answer
 
Comments
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