Sunday, March 13, 2011

Understand and Implement jQuery getJSON

getJSON function is used to get JSON data from server using an AJAX HTTP GET request.
What is JSON, JSON is JavaScript Object Notation which is an open standard designed for data interchange. JSON is a collection of key value pairs.

Syntax

$.getJSON(url, data, success(data, status, xhr)) { 
//code to be executed when request succeeds
});


Description of Parameters
ParameterParameter TypeDescription
url Mandatory Requested url to call. It can be an api or url or a javascript file
data Optional Data to send with request. Its a key value pair
success(data, status, xhr) Optional Code to run if request succeeds.
data value that return with the request
success contains a string containing request status that can be success, notmodified, error, timeout or parsererror
xhr have XMLHttpRequest object

Implementation

I will show you two examples of getJSON function first one will call Flickr api and second will be used in ASP.NET MVC

1. Using getJSON get Flickr images
Below example will get 5 images from Flickr using getJSON function and append them in a div having id divid also it sends two parameters with the request one is tags and other one is format.
jQuery Code
$(document).ready(function () {
 $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?  jsoncallback=?",
 {
 tags: "cat",format: "json"},
 function (data) {
  $.each(data.items, function (i, item) {
  $("<img/>").attr("src", item.media.m).appendTo("#divid");
  if (i == 4) return false;
  });
 });
});



2. Using getJSON in ASP.Net MVC
Because i use getJSON in Asp.net MVC ill show you how to implement in it using C#.
jQuery Code
$(document).ready(function () {
 $.getJSON("/Json/GetJson", { }, function (data) {
  $.each(data, function (key, value) {
   $("#content").append(key + ": " + value + "<br/>");
   });

  });
 });
});


Controller Code
public JsonResult GetJson()
{
 Dictionary objDic = new Dictionary();
 objDic.Add("First Name", "Fraz");
 objDic.Add("Last Name", "Sundal");
 objDic.Add("Job Description", "Web Engineer");
 return Json(objDic, JsonRequestBehavior.AllowGet);
}


It calls a controller action name GetJson and resultant is a key value pair having keys First Name, Job Description and Last Name which is then embedded in to a div named content. When returning Json in controller you have to specify JsonRequestBehavior.AllowGet otherwise it will display an error which says This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
To watch getJSON request process you can use Firefox popular add-on Firebug. It takes 1.09 sec and Status code is 200.

Firebug Screen Shot