Sunday, March 20, 2011

AJAX + JSON

Hi,

JSON is a very lightweight script which is used to store data. It is useful because of its speed. Calling and working with JSON is much faster as compared to XML. This post deals with calling a JSON file via AJAX and parsing it accordingly.

To begin with we have the following json file, student.json with the following content:


{"students": [
        {"Name": "John Smith", "Age": "18", "Gender": "male"},
        {"Name": "Maratha", "Age": "19", "Gender": "female"},
        {"Name": "Rose", "Age": "17", "Gender": "female"},
    ]}

This of course is a sample data which I created manually. Now to call this file via ajax I will be using jQuery. Now I create a new file example.php and make a ajax call to the above "student.json" as follows:


jQuery(document).ready(function(){
jQuery.ajax({
type:"GET",
url: "student.json",
success: function(content){
.............
}
})
})

In the above example I am calling the json file after the entire page has been loaded in the browser. After the ajax call successfully executes, this is what I am doing:


success: function(content){
var students_json=eval("("+content+")");
total_students=students_json.students.length;
for(i=0;i<total_students;i++){
jQuery("body").append("Name: " + students_json.students[i].Name+ "  Age: "+students_json.students[i].Age+"  Gender: "+students_json.students[i].Gender+"<br>");
}
}

"eval()" function is used to convert a string into a JSON script. Next "students" is the name of the main root element. I am first finding the content length of "student", later I am executing a loop and extracting 1 field at a time and displaying the values in the web page. This is the output I get:




Click here to download the entire source code of this example. This mechanism is used by various popular sites with lot of custom encryption. But this is the basic idea.

Hope this helped.


1 comment:

  1. Thanks For posting . Its Really nice . Keep update a more article.Thanks for sharing the knowledge.

    Website Security

    ReplyDelete