Ajax/jQuery.getJSON Simple Example

Sam Deering
Tweet

json

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)

json-jquery.js

$(document).ready(function(){
	//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
			$('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>");
		});
	});
});

json-data.php

< ?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.

page.html

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns=" http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request json test</title>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script src="json-jquery.js" type="text/javascript"></script>
</head>
<body>
<a href="#" id="getdata-button">Get JSON Data</a>
<div id="showdata"></div>
</body>
</html>

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.

$.ajax({
	 type: "GET",
	 url: filename,
	 async: false,
	 beforeSend: function(x) {
	  if(x &amp;&amp; x.overrideMimeType) {
	   x.overrideMimeType("application/j-son;charset=UTF-8");
	  }
 },
 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:

{
    "a":1,
    "b":2,
    "collection":[{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    }]
}

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.

{
    "settings":
    {
        "maxResults": 10,
        "resultsPerPage": 10
    },
    
    "map":
    {
        "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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Raicha

    Very useful
    Thanks!

  • Pingback: 10 Example JSON Files | Web Design Northamptonshire

  • Peter

    Thanks! Your json-data.php was the key for my problem: Prototype uses a different way to submit the result…

    • http://jquery4u.com/ jQuery4u

      Your welcome Peter!
      Sam

  • Pingback: jQuery.ajax get json code snippet | jQuery4u

  • Pingback: jQuery.ajax get json code snippet » PHP Script Blog

  • alex

    sorry i have a problem it does’nt work, do i need something extra or some server config?

    • jquery4u

      @alex,

      Can you give me more details about what your trying to do? Remember ajax abides to the cross domain policy. You can also ajax things from inside your own domain unless you use JSONP or have a proxy pass in place between the domains.

      It’s hard to determine the problem without more information about what your trying to achieve.

  • Pingback: 10 jQuery Tabs Tutorials | jQuery4u

  • Jesus

    Thank you for your post, it was really helpfull

    if you are trying to pull info off a database, you can do this

    $sqlstring = “SELECT image FROM graphics WHERE field = ‘$value’ AND anotherfield = ‘$anothervalue’ ORDER BY position;”;
    $links = mysql_query($sqlstring) or die(mysql_error());
    while ($row = mysql_fetch_assoc($links)) {
    $jsons[] = $row;
    };

    echo json_encode($jsons);

    //then on the javascript side you can do

    for(var i = 0; i < data.length; i++){
    alert(data[i].image); //you can easily have a nice array and if you have more fields on the database you just say data[i].otherfield
    }

  • chouchou

    Thanks for the exposition. I learnt some new things

  • Said Suleiman

    Thanks alot for this tutorial, i know what my mistake was i was missing the $_GET['callback'] .'('.jscon_encode($json).')'; in my code and experienced the problem for at least 3 weeks now, i googled alot, final u helped me.

    • http://jquery4u.com/ jQuery4u

      No worries mate glad it helped.

    • Rajesh

       said … Could you please explaing me Where do i have to paste this code?

      • Said Suleiman

        at the end of your php when u’re echoing the json data i.e.
        echo $_GET['callback'] .'('.json_encode($json).')';

  • vimlesh jaiswal

    very usefull
    thanks.

  • Pingback: 10 jQuery Ajax Tab Plugins | jQuery4u

  • tarek

    it shows ”
    item1=undefined item2=undefined item3=undefined” in
    showdata any help?

    • http://jquery4u.com/ jQuery4u

      Hi Tarek,
      Can you paste your code into a jsfiddle.net for me to check it for you.

      Thanks,
      Sam

  • lost in scope

    great tuorial! Many thanks from estonia

  • Alechandrina Pereira

    Really good post, thanks a lot :)

  • Pingback: Enumerating through Yahoo Pipes generated JSON with jQuery fails | Jisku.com

  • http://www.facebook.com/axelbrice Axel Brice

    Thanks for this post; it’s useful but i got some troubles :it shows “item1=null item2=null item3=null” in
    showdata any help? ( data of json array are pulled info off a database). please can i have some help ?

  • http://www.facebook.com/people/Michael-Eng/100001734508347 Michael Eng

    The php script has a few bugs: 1) the items should be in quotes, 2) there should be commas that separate each name-value pairs.

  • Jeric

    At last a simple example – its taken me a while but i’m getting there – cheers

  • Mike

    Your first step titled “JSON jQuery Syntax” — What does it mean? Where does it go? Is it a part of the same exercise that involves the 3 files (php, JS, HTML) that we need?

  • test

    Nice tutorial.
    Though I was expecting a little more about jQuery based processing of JSON response

  • Pingback: Using PHP to return JSON data to Jquery Ajax | limxinyangray

  • gzb

    thanks for this – i’m new to ajax and php and this is the first guide i’ve seen that actually worked.

  • Martiny

    Greetings. Your example code for json-data.php have some mistakes. JSON output of this code can not get validation, because variable name (tag) will need quoted. Right example:
    //return in JSON format
    echo ‘{‘;
    echo ‘”item1″:’, json_encode($item1), ‘, ‘;
    echo ‘”item2″:’, json_encode($item2), ‘, ‘;
    echo ‘”item3″:’, json_encode($item3);
    echo ‘}';
    Have a nice day! Your example was helpfully.

  • Pingback: JQuery: getJSON not working at allCopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query, update query, i

  • Pingback: JQuery: getJSON not working at all - QueryPost.com | QueryPost.com

  • hkjhj

    gh gh jglhg g g