Ajax Data - HTML vs. XML vs. JSON

December 19th, 2008   Filed Under Good to know, Javascript, Thinking Out Loud, Tips & Tricks, gyan, json  

Ever wondered why Ajax stands for ‘Asynchronous Javascript And Xml’? I was thinking about it and realized that the ‘x’ is never used or let us say of almost no use.

Classically when introduced by Microsoft, xmlhttprequest object might have been thought to  transport XML for the data transfers, as that was the most popular format which was known as the lightest in weight. But they forgot about the json.

Moreover, the scenario where we are standing today is really different than what had been thought earlier.

What was needed classically was to make a hidden request - get the response - inject in html - and show the result. But for this people started using the xmlhttp object as htmlhttp object. I mean rather than only transporting data, they are using HTML strings attached with the data(or the other way round).

I will show how can we make the request and response lighter and show results faster on the page so that the users don’t have to wait even on the dial up connections.

First let us compare the strings that are sent in a response in different formats.

HTML:

<div class=”resultArea”><h3>This is the result of  your query</h3><p><span>Request Num:</span>4564545<br/><span>Status:</span>Pending</p></div>
XML:

<resultArea>
    <heading>This is the result of your query</heading>
    <requestNum>4564545</requestNum>
    <status>Pending</status>
</resultArea>


JSON:

{heading:”This is the result of your query”, requestNum:”4564545″, status:”Pending”}

Clearly you can see which one uses less number of characters.
Not only that, you are only an eval() away from start using the object with the luxury of (.) dot notations. What else do you need?

Had we been using HTML,  we would have transported unnecessary HTML text along with the pure data to the browser. Just imagine the amount of repetitive HTML in case of a tabular data.

Using XML is also not so convinient because besides being bulky with its starting and ending tags, it is also needed to read via the DOM to traverse through the XML, which is time consuming, resource hungry and inconvinient code.