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.

{
“productname”:”Java”,
“productdesc”:”java/jsp editor”,
“productprice”:650,
“validity”:”1 Year”
}

Example:

function sendAjaxRequest(url, divid)
{

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

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 https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/

Also want to know about JSON, go here to learn basics https://manikandanmv.wordpress.com/2008/10/08/json-java-script-object-notation/

Tags: , , , , , ,

Leave a comment