Web Info and IT Lessons Blog...

Saturday 30 May 2015

Jquery $.ajax() method to read json data

JQuery Ajax Method

If you want to read a json file containing data in json format without refreshing the page, then you need to make an ajax request to the json file using jquery $.ajax() method. Let us say we have a json file we want to read containing data in json format given below:


{"Students":[
    {"firstName":"John", "lastName":"Albert"},
    {"firstName":"Anna", "lastName":"Gomez"},
    {"firstName":"Peter", "lastName":"Jones"},
    {"firstName":"Michelle", "lastName":"Simmons"},
    {"firstName":"Ricardo", "lastName":"Smith"}
]}

Now let us make an ajax call to data.json file and read it's contents using $.ajax() method. Once we have the json data available in javascript, we will append the data to the html body:

Html Code:

<input type="button" value="Make Ajax Call" onclick="ajaxCall();" />
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

In the above html code we have created a button and attached onclick event to it. In the next step we have included jquery in our web page.

Note: Including jquery in your web page is necessary for $.ajax() method.

Javascript Code:

<script type="text/javascript">
function ajaxCall(){
   $.ajax({
   url: 'data.json',
   type: 'GET',
   dataType: 'json',
   data: {},
   success: function(data){ 
 var arrSize = data.Students.length;
 for(var i=0;i < arrSize;i++){
    var name = data.Students[i].firstName+' '+data.Students[i].lastName;
    $("body").append('<br />'+name);
 }
   }
  });
}
</script>

The above javascript code makes an ajax call to data.json file and read it's data. Javascript for loop is used append all the data in the json array to the html body.

Stay tuned for more lessons...

No comments:

Post a Comment