How to get JSON data easily using jQuery [AJAX]

AJAX is such a powerful technique which helps for creating fast and dynamic web pages. It allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
And to implement AJAX, you cant believe how jQuery has made that easy. There is now no need of writing browser dependent Ajax code. jQuery will take care of that.

While retrieving data from server side through ajax, we can use different various types of datatypes like html, text, xl, json, etc. I want to show here an short and simple example of using ajax and jquery and you will me amazed how easy that is. Lets grab the twitter feed of an id in the json format using ajax and jQuery. I have used $.getJSON for simplicity. You can use $.ajax in more flexible way with more parameters.

DEMO

$.getJSON("https://twitter.com/statuses/user_timeline.json?screen_name=nilambar&count=5&callback=?",
function(data){
  var output  ='';
  $.each(data, function(i,item){
  t_text = item.text;
  t_time = item.created_at
  t_source = item.source;
  output+= '<p>' + t_text+'<em>'+t_time+'</em> via '+t_source+'</p>' ; 
});
 $('#tw').html(output);//replacing html in the output div
});

In this example, there is only two parameters in $.getJSON function. Other required parameters in the ajax call will be handled by jQuery itself. One is the URL to be called and other is the callback function which will be called after successfull ajax event. After getting JSON response, $.each is used to access it and make output text ready. Then the html is replaced in the div.
 
DEMO
So if you are planning to use AJAX in your application and you are cosidering to use javascript library then jQuery would be one of your best options.
Its easy. Go and try it.

Photo : tutsplus.com

Leave a Reply

Your email address will not be published. Required fields are marked *