Using JSON in Ajax

Send an Ajax request to server and get a server response as JSON formatted object. JSON is an alternative of XML format. Lets see the below code for retrieving the data from JSON formatted object.

Assume the response text should be like this.

“productdesc”:”java/jsp editor”,
“validity”:”1 Year”


function sendAjaxRequest(url, divid)

url = url + getNoCacheValue(url);
var req = getXMLHttpRequest();
req.onreadystatechange = function(){ processResponse(req, divid) };‘GET’, url, true); // GET type request.

function processResponse(req, divid)
if (req.readyState == 4) {
if (req.status == 200) {
var prod = req.responseText;
// retrieve data from JSON formatted response text.
var prod_name = prod.productname;
var prod_desc= prod.productdesc;
var prod_price = prod.productprice;
var prod_val = prod.validity;
// write your code here to show the above retrieved values.

Suppose if you want to execute the scripts present in the response text, use the javascript eval function.

If  you are new to ajax, pls read this

Also want to know about JSON, go here to learn basics

Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: