Ajax Response Data Formats

Some time ago, Peter Paul Kosh wrote an article about the different types of Ajax data formats - The AJAX response: XML, HTML, or JSON?. The response format is the format in which the data is sent from the Server side to the client side. There is another format to send data from the client side to the server side - UED(Url Encoded Data).

The popular formats for sending data from server side to the client side are...

JSON

I prefer JSON as it is the easiest to parse - just put an 'eval' and we are done. My biggest issue with this is the text created by the server-side script is next to unreadable by human beings. This makes it very hard to debug our Ajax scripts.

Another problem with this approach was the difficulty of creating the JSON string at the server side. But now this is not very hard as PHP 5 has added support for the json_encode() function. If you are using an older version, there are a lot of third party functions available - like array2json(). If you are using Ruby on Rails, you can do the same with data.to_json.

Text

My second favorite place goes to plain text format as it is the easiest to generate. I use plain text only when there is just a single unit of data - when I want the email address of an user from the database or if I want to know wether the given username exists in the database - the response data will be just a '1' or a '0' in this case.

AHAH

Next in line comes the HTML format - the easiest to display. $("display").innerHTML = http.responseText is all it takes to get the job done. This method is commonly known as AHAH.

XML

Last but not the least comes the XML format - the most portable solution. All major languages has built in support for XML - so it should not be very hard to generate. However, in JavaScript, XML format is the most difficult to parse.

Again, there are functions that will make this much easier - like my xml2array() function.

Other Formats

There are many other formats that can be used for this purpose. However, the above four are the most popular. The other formats include...

blog comments powered by Disqus