Ajax/jQuery.getJSON Simple Example


What is JSON and why use it?

JSON stands for JavaScript Object Notation. In simple terms JSON is a way of formatting data to
We will look at loading JSON data using an HTTP GET request (you can also use POST).
You may be thinking why you would choose JSON over say XML? See Why use JSON over XML?

Where to start?

Ajax DemosJSON Files Examples

JSON jQuery Syntax

jQuery.getJSON( url, [ data ], [ success(data, textStatus, jqXHR) ] )

url – A string containing the URL to which the request is sent.
data – A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR) – A callback function that is executed if the request succeeds.

What you need (included in download source files)

  1. json-jquery.js – js file to request the data
  2. json-data.php – php file to connect to database to retrieve data
  3. page.html – html page to call/display data

Download Example (Source Files)


	//attach a jQuery live event to the button
	$('#getdata-button').live('click', function(){
		$.getJSON('json-data.php', function(data) {
			//alert(data); //uncomment this for debug
			//alert (data.item1+" "+data.item2+" "+data.item3); //further debug

item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"

"); }); }); });


< ?php
//request data from the database
//code here to connect to database and get the data you want

/* Example JSON format
  "item1": "I love jquery4u",
  "item2": "You love jQuery4u",
  "item3": "We love jQuery4u"

//return in JSON format
echo "{";
echo "item1: ", json_encode($item1), "n";
echo "item2: ", json_encode($item2), "n";
echo "item3: ", json_encode($item3), "n";
echo "}";

Alternative methods
Create an array in PHP and use the json_encode() function to encode the whole array.

< ?php
$arr = array ('item1'=>"I love jquery4u",'item2'=>"You love jQuery4u",'item3'=>"We love jQuery4u");
echo json_encode($arr);

This will output the array in the correct JSON format, however it may not include line breaks as the previous example shows so make sure you check this by alerting the data. There is also a json_decode() function which does the opposite.


< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

Get JSON Data

jQuery .ajax() method

This is an awesome method, probably my preferred way of calling a JSON file because you can explicitly set all your options. Adjust async to true if you want this to AJAX call to run at the same time as other things.

	 type: "GET",
	 url: filename,
	 async: false,
	 beforeSend: function(x) {
	  if(x && x.overrideMimeType) {
 dataType: "json",
 success: function(data){
	//do your stuff with the JSON data

Don’t forget to validate your JSON

There is an online JSON Validator tool called JSONLint you can use to validate your JSON files.

Other JSON Tutorials

See Load Flickr Pictures using JSONP API

Convert a PHP Class to JSON
As json_encode() is recursive, you can use it to serialize whole structure of objects.

< ?php
class A {
    public $a = 1;
    public $b = 2;
    public $collection = array();

    function  __construct(){
        for ( $i=3; $i-->0;){
            array_push($this->collection, new B);

class B {
    public $a = 1;
    public $b = 2;

echo json_encode(new A);

Will give:


How to fix JSON errors

  • Make sure the JSON returned by the PHP is in the correct JSON format.
  • Try using $.get instead of $.getJSON as it might be your php is not returning valid JSON.
  • Check the data that is being returned by alerting the data.

Common $.getJSON errors

  • Using the jquery.validate.min.js plugin sometimes causes JSON to stop working, not sure why.
  • Silent failures on $.getJSON calls: This might happen if your jsoncallback=json1234 (say) and if the ‘json1234(…)’ does not exist in the json results, the $.getJSON will silently error.
  • Uncaught SyntaxError: Unexpected token :(in crome) Invalid Lable(in firefox)
    “invalid label” error can be fixed by passing the JSON data to the js callback
$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';

More JSON Examples

JSON file to hold Google Map Settings.

        "maxResults": 10,
        "resultsPerPage": 10
        "center": [-28.164139071965757, 133.75671386718753],
        "zoom": 4,
        "icon": ""

Further Reading and JSON Links

Converting JSON data to tables: http://labs.adobe.com/technologies/spry/samples/data_region/JSONDataSetSample.html