Sending JSON data array to Javascript

Created March 24, 2011

Let's say that we wanted to send an Ajax or jQuery post to a page and we wanted to receive an array of values back. What would be the easiest way, you may ask yourself? Well, the answer is JSON. If you are not familiar with JSON, it is merely a text dump similar to XML, which can easily be read by multiple technologies. For further reading of JSON checkout What is JSON.

Okay, lets say you want to get data from a database via PHP and then pass the data to Javascript. Well, your PHP code would look similar to this:


// initialize any additional resources you need
// get data from database and put values into $rows

 $json = array();
 foreach($rows as $row):
      $arr = array(
      'id' => $row['id'],
      'name' => $row['name']
 array_push($json, $arr);
 $jsonstring = json_encode($json);
 echo $jsonstring;


In the PHP code above while looping through your database rows, you create and push a new array value. Finally at the end you encode the array and echo out the value. Next retrieve these values from a jQuery Post to the above page, you would use the following Javascript code:

function get_json_values()
       $.post('url_to_page_above.php', function(json) {
	   	var json_string = eval(json);
		for(var i=0; i < json_string.length; i++){

The above code will alert all the values that were queried by the the PHP in the first code. This is a basic example of how you can use Javascript to call a PHP page, then receive the information back in Javascript and use the data however you desire ;)