jQuery.getJSON() Example

If you are creating an Ajaxy web application jQuery offers a few great methods to help you out. In this tutorial I will demonstrate one of those; the getJSON() function. I’ll create a simple example of how this wonderful powerful, yet beautifully simple function can be used.

jQuery’s getJSON() function was created to retrieve JSON-encoded data from a server. It’s actually just shorthand for the ajax() function.

I’ll start by saying that I personally love JSON and generally prefer it to XML when transferring data with Ajax requests. By nature its structure is generally less bloated than XML, therefore reducing data transfer bandwidth. It’s easy to use. And it translates directly to Javascript objects.

OK, so on to the example. Download the minified version of the jQuery library at jQuery.com. Save the file in your web root as “jquery.js”.

19% Price Drop: Panasonic 47" Silver 1080P 3D LED HDTV With Built In Web Browser – TC-L47DT50

Next, create a new file called “index.html” in your web root directory and put the following inside it.

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
 
    </script>
</head>
<body>
    <button id="requestDataBtn">Get Data</button><br />
    <textarea id="results" style="width:400px;height:350px;border:solid 1px black;"></textarea>
</body>
</html>

The markup above gives us a very simple web page with the jQuery file referenced, a section of Javascript in the “head” where we can write our Javascript code, and a button element. We also have a textarea where we will show the results of our requests. Let’s add a click event handler to the button that will make our Ajax request using the “getJSON” function. Put the following in the head script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function(){
    $('#requestDataBtn').click(function(){
        $.getJSON('getPeople.php', { minimumAge: 21 }, function(data, textStatus, jqXHR){
            // Success handler.
            // We expect something from the server like this:
            // { people: [ { name: 'Robbie', age: 24 }, { name: 'Sarah', age: 29 } ] }
 
            // Display the data.
            for(var i = 0; i < data.people.length; i++){
                var newText = $('#results').val() + "\n";
                newText += 'Name: ' + data.people[i].name + ', Age: ' +
                data.people[i].name;
            }
        });
    });
});

A few things happen in the code above. First, we use the ready() function, much like we might use the document.onload event handler. Inside this handler we add a click event handler to the button. When the button is clicked we make a call to getJSON(). There are a couple options with the parameters of getJSON(). In this example we define the name of the request web resource/page. Next we define an object (using JSON) with data we want to give the backend as a filter for our results. The third parameter defines our success handler. We expect the resulting data to be in a certain format as you can see in the code above. If we have the proper format then our example should create a new line for each “person” received in the request result.

Note that this function uses the jQuery.ajax() method, and will always convert any data sent into a querystring (GET), rather than a POST.

The complete web page should look like this:

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
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#requestDataBtn').click(function(){
                $.getJSON('getPeople.php', { minimumAge: 21 }, function(data, textStatus, jqXHR){
                    // Success handler.
                    // We expect something from the server like this:
                    // { people: [ { name: 'Robbie', age: 24 }, { name: 'Sarah', age: 29 } ] }
 
                    // Display the data.
                    for(var i = 0; i < data.people.length; i++){
                        var newText = $('#results').val() + "\n";
                        newText += 'Name: ' + data.people[i].name + ', Age: ' +
                        data.people[i].name;
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="requestDataBtn">Get Data</button><br />
    <textarea id="results" style="width:400px;height:350px;border:solid 1px black;"></textarea>
</body>
</html>

That’s it for this example. Hopefully this has given you a better understanding how the jQuery.getJSON() function works and how you might use it in your own web applications. Have fun coding.