Tuesday, October 22, 2013

jQuery: AJAX and JSON

In this post, we will learn jQuery AJAX using JSON data. The term JavaScript Object Notation (JSON) was coined by Douglas Crockford to capitalize on the simple syntax. JavaScript Object are just sets of key-value pairs, and can be defined succinctly using curly braces ({}). JavaScript arrays are defined on the fly with square brackets([]). Combining these two concepts will express some very complex and rich data structures.
Following Simple example JSON. This notation can offer a concise alternative to the sometimes-bulky XML format:
1{
2  "key": "value",
3  "key 2": [
4    "array item 1",
5    "array item 2",
6    "array item 3"
7   ]
8}
For more complex data, see code below:
01[
02{
03    "company" : "Toyota",
04    "product" : "Prius",
05    "color" : [
06      "white pearl",
07      "Red Methalic",
08      "Silver Methalic"
09    ],
10    "type" : "Gen-3"
11},
12{
13    "company" : "Toyota",
14    "product" : "New Fortuner",
15    "color" : [
16      "Super White",
17      "Silver",
18      "Black"
19    ],
20    "type" : "Fortuner TRD Sportivo Limited Edition"
21}
22]
Save above code. Named "data.json". We will use it to our jQuery AJAX using JSON in this post.
To call data.json and access data. You can use following code:
1$(document).ready(function() {
2  $('#element').click(function() {
3    $.getJSON('data.json');
4    return false;
5  });
6});
For more complex data, such as above data, we can use:
01$.getJSON('data.json',function(data){
02    $('#content').empty();
03    $.each(data, function(entryIndex, entry){
04        var html = '<div class="data">';                   
05        html += '<h3>' + entry['company'] + '</h3>';
06        html += '<div class="product">' + entry['product'] + '</class>';                   
07        html += '<div class="type">' + entry['type'] + '</color>';                                     
08        $('#content').append(html);
09    });                       
10});
To be more clear, try this code. Save as "page.html". Place along with "data.json".
01<html>
02<head>
03    <style type="text/css">
04         
05    </style>
06    <script src="jquery.js" type="text/javascript"></script>
07    <script type="text/javascript">
08    $(document).ready(function() {
09        $('#car').click(function() {
10            $.getJSON('data.json',function(data){
11                $('#content').empty();
12                $.each(data, function(entryIndex, entry){
13                    var html = '<div class="data">';                   
14                    html += '<h3>' + entry['company'] + '</h3>';
15                    html += '<div class="product">' + entry['product'] + '</div>';                 
16                    html += '<div class="type">' + entry['type'] + '</div>';                                       
17                    $('#content').append(html);
18                });                       
19            });
20            return false;
21        });
22    });
23    </script>
24</head>
25<body>
26 
27<a href="#" id="car">Car</a>
28<div id="content">
29</div>
30</body>
31</html>

To handle the entries with colors, which takes another $.each() loop
01$(document).ready(function() {
02    $('#car').click(function() {
03        $.getJSON('data.json',function(data){
04            $('#content').empty();
05            $.each(data, function(entryIndex, entry){
06                var html = '<div class="data">';                   
07                html += '<h3>' + entry['company'] + '</h3>';
08                html += '<div class="product">' + entry['product'] + '</div>';                 
09                html += '<div class="type">' + entry['type'] + '</div>';
10                if(entry['color']){
11                    html += '<div class="color">';                                           
12                    html += '<ol>';
13                    $.each(entry['color'],function(colorIndex, color){
14                        html += '<li>' + color + '</li>';                         
15                    });
16                    html += '</ol>';                     
17                    html += '</div>';                                            
18                }
19                $('#content').append(html);
20            });                       
21        });
22        return false;
23    });
24});