jQuery AJAX JSON Example – jQuery.parseJSON(), $.post() & $.getJSON()

In jQuery AJAX JSON Example, I have explained how to handle GET and POST JSON requests using jQuery API.

Topics Covered.
1). Encode Object to JSON String
2). Parse JSON String using jQuery
3). Handling JSON GET requests using $.getJSON()
4). Handling JSON POST requests using $.post()

1). Encode Object to JSON String

JSON stands for JavaScript Object Notation. i.e String representation of javascript Object.
Let us take a Javascript object

var obj = {};
    obj['name']='hayageek'; //string
    obj['age'] = 32;  // integer.
    obj['marks']= [80,70,60,50,60,80]; //array

Above object is represented as below JSON string.

{"name":"hayageek","age":32,"marks":[80,70,60,50,60,80]}

In PHP, JSON string is generated using json_encode function.

<?php
$obj = array();
$obj['name']='hayageek'; //string
$obj['age'] = 32;  // integer.
$obj['marks']= array(80,70,60,50,60,80); //array
echo json_encode($obj);
?>

In Python, JSON string is generated using json.dumps() function.

import json
obj = {'name':'hayageek','age':32,'marks':[80,70,60,50,60,80]};
print json.dumps(obj);

In Ruby, JSON string is generated using to_json method.

require "rubygems"
require "json"
obj = { 'name' => 'hayageek','age' => 32,'marks' => [80,70,60,50,60,80]}
print obj.to_json

In .NET, you can use JavaScriptSerializer().Serialize(obj) method to encode an object to JSON.

2). Parse JSON String using jQuery.

JSON string can be converted to JavaScript Object, using jQuery.parseJSON() function.

var obj = $.parseJSON('{"name":"hayageek","age":32,"marks":[80,70,60,50,60,80]}');
    obj.name //Name
    obj.age  //Age
    obj.marks[0];//first mark

We can use JSON.stringify() method to convert JavaScript Object to JSON string.

var obj = {"name":"hayageek","age":32,"marks":[80,70,60,50,60,80]}
var jsonString =JSON.stringify(obj);

3). Handling JSON GET requests using $.getJSON() API.

You can useĀ  $.getJSON() API, to handle JSON HTTP GET requests.

Syntax:

jQuery.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )

url : URL which handles GET requests.
data: data to be sent to the server.
success:callback function to be invoked when the request is successful.

jQuery AJAX JSON GET Examples:

var getParams={ q:"SELECT uid,name FROM user WHERE uid =100000982091583" };

$.getJSON("https://graph.facebook.com/fql",getParams,
	function(data, textStatus, jqXHR)
	{
 	        //data is an object.
		data.data[0].uid;
	});

$.getJSON("https://graph.facebook.com/fql?q=SELECT%20uid,name%20FROM%20user%20WHERE%20uid%20=100000982091583",
		function(data){
		//data is an object.
		//data.data[0].uid

});

Note: JSON String from the server is automatically converted to JSON Object.

jQuery.getJSON() does not have any option to handle error case. Errors can be handled with jQXHR fail() callback.

$.getJSON("https://graph.facebook.com/fql?q=SELECT%20uid,name%20FROM%20user%20WHERE%20uid%20=100000982091583",
	function(data, textStatus, jqXHR)
	{
		//data is an object.
		//data.data[0].uid;
	}).fail(function(jqXHR, textStatus, errorThrown) 
{
  //error
});

jQuery AJAX JSON GET Demo

 

2). Handling JSON POST requests using $.post()

jQuery $.post() automatically converts JSON string to javascript object, if the response Content-Type is “application/json” or “text/json”. Otherwise you need to set dataType to “json”.

 

jQuery AJAX JSON POST Example:

var postData={x:1,y:2};
$.post("http://AJAX_POST_URL",
	postData,
	function(data, textStatus, jqXHR)
	{
	    //data - JSON object from server.
	},"json").fail(function(jqXHR, textStatus, errorThrown) 
		{

		});

jQuery AJAX JSON POST Demo

 

Reference: jQuery API Documentation