
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 Demos
JSON 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)
- json-jquery.js – js file to request the data
- json-data.php – php file to connect to database to retrieve data
- 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 && 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






Very useful
Thanks!
Thanks! Your json-data.php was the key for my problem: Prototype uses a different way to submit the result…
sorry i have a problem it does’nt work, do i need something extra or some server config?
@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.
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
}