Saturday, August 04, 2007

AJAX response: HTML, XML, JSON

Its fun to have the partially refreshing dynamically modifiable page using AJAX, both for application developer and for application user. But as a application developer parsing the partial response from server and dynamically modifying the DOM can become very complicated, parsing the response itself can be very tedious. Though the 'X' in AJAX stands for XML but your response need not be XML, it could be any text format, for our discussion we consider following three text response types

  • HTML/plaintext
  • XML
  • JSON
If you just need to modify one section of page and can use the response as is, then its no-brainer, you simply use HTML or plain text response. e.g. if you build expand collapse control where you want to display some information in a div/span you just get processed HTML from server and use it as follows in you onreadystatechange event handler:
var expandAreaDiv= document.getElementById("expandAreaDiv");
But life is not this simple always :-). As you application matures need arise to modify multiple section of the page with one response. One response and multiple modification means you can no longer use the response as is, you have to parse the response. By default we tend to use XML as the only option; after all 'X' in AJAX stands for XML :-)
Take a simple example, if you performed update of some entity using AJAX than probably you need to do following
if success
update the status field
show the success message
show the failure message
So bare minimum you need three separate informations from server in one response
boolean value indicating success/failure
String value containing the message response
String value containing the new Status
So you decide to have XML like this


and in javascript you parse the response to get values into variables and then use it..
var response= req.responseXML.getElementsByTagName('myResponse');
var isSuccess = getNodeValue(response,'isSuccess');
var newStatus= getNodeValue(response,'newStatus');
var message= getNodeValue(response,'message');
function getNodeValue(obj,tag){
return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
and as your XML becomes complex parsing becomes more complex and you start looking for some parsing tools. This is where i like JSON, which stands for JavaScript Object Notation. Your JSON response would look like this:
"isSuccess" = true,
"message" = "Successfully updated the Status",
"newStatus = "Active"

and here is you response parsing code in JS:
var response = eval( '('+req.responseText + ')' );
and voila you can acess response.isSuccess, response.newStatus, response.newStatus. All parsing is done for you just by eval().

Be careful that you take care of JSON special character " and control characters like CR NL in the generated response.
e.g. "message" = "Successfully
updated the Status",
will not work. JSON is not as readable as XML, but its more readable for computer :-) . Though I could not find any powerful JSON editor but this one is useful.

Finally, as far as security is concerned JSON by itself is just a data format (like XML) so it is secure, but the eval function is not, so if someone could inject malicious script into your JSON, that would get executed on to the client. So make sure you validate the data before you put into JSON response (this you should do anyway if you need your application to be secure).


Ashish said...

The most important advantage is that JSON circumvents JavaScript's same-source policy, if you import the JSON file as a new script tag.

JavaScript does not allow you to access documents (be they XML or HTML) that come from another server. However, if you import a JSON file as a script tag you circumvent this problem, and any JSON data can be imported into any website. It depends on your business goals whether this is a Good or a Bad Thing, but right now it's the only data format that allows unrestricted access.

Anurag Jain said...

You are mixing dynamic script tag and XMLHttpRequest. XHR will never permit cross domain access no matter what data you are using XML/HTML/JSON or any XYZ data format.

Using dynamic script tag you can load data in any format and use it inside the script, only thing is JSON makes it very simple. As it would make any response processing inside the javascript code.