05 - AJAX data formats

Upon sending an XMLHttpRequest request to the server, we will have a response. This response could be in two different formats: plain text or in XML.

- Plain text: we could receive just a text, a word, a sentence (JSON is actually a sentence)

- XML: the response we received will be XML encoded, so our JavaScript may need to perform some transformation to display it.

XML

The eXtensible Markup Language was created to provide some structure to the information exchanged between multiple systems. It provides a way to store this information and to transport it.

Basically with XML you could create your own language to store your information, for instance:

<record>
    <from>John Doe</from>
    <to>Everyone</to>
    <title>First XML Record</title>
    <description>This is the first of many XML records</description>
</record>

To access an XML response, the XMLHttpRequest object has a property called: responseXML.

Once you have the response in a JS variable, you can access the different nodes of the XML with standard DOM functions: i.e: getElementsByTagName.

String

As mentioned before, an XMLHttpRequest could receive plain text as a response: a word, a letter, a complete sence, and text with special encoding. To access this response you have to use a property called: responseText.

This method would be used for receiving short fragments of information or as we will see next, JSON objects.

JSON

JSON stands for JavaScript Object Notation which is a data interchange format. It is now widely adopted as a way to handle responses from server, since it is a simple encoding that allows human and machines to read it easily.

In our tutorial, as I briefly mentioned before, a JSON response is actually a text response, so you should use the responseText property to access it. Once you have it available, you could use multiple JSON libraries to parse it, and perform any operation needed based on the information received.

For more information about JSON, you could visit: http://www.json.org/

Like us on Facebook