Thursday 11 September 2014

Ajax/jQuery.getJSON Simple Example..Json Example

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?

JSON jQuery Syntax

1
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

json-jquery.js

1
2
3
4
5
6
7
8
9
10
$(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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
< ?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.
1
2
3
4
< ?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

1
2
3
4
5
6
7
8
9
10
11
12
13
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.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

Convert a PHP Class to JSON
As json_encode() is recursive, you can use it to serialize whole structure of objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
< ?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
1
2
$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';

More JSON Examples

JSON file to hold Google Map Settings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
    "settings":
    {
        "maxResults": 10,
        "resultsPerPage": 10
    },
     
    "map":
    {
        "center": [-28.164139071965757, 133.75671386718753],
        "zoom": 4,
        "icon": ""
    }
}

Further Reading and JSON Links

No comments:

Post a Comment