Despite XMLHttpRequest (XHR) has a responseXML property, processing XML is relatively unpopular in Ajax application. The more favorable variant is JavaScript Object Notation aka JSON. Similarly to XML, JSON is also structured file, the word "structured" simply means it is properly formatted, it's easier for machine to read. In compared to XML, JSON is harder for human to read, it's not completely unreadable but just harder.

Let's take the movies.xml we've seen in previous page and turn it into a JSON file that contains the exactly same data. Here is how the JSON file movies.json looks like.

Now, XMLHttpRequest has responseXML property but there isn't a responseJSON. We have got to use responseText property for JSON.

Let's fetch the first movie title from the JSON file asynchronously.

movies xml file

We are still using these same 3 steps :-

  1. Step 1 Instantiate / Create an XHR instance
  2. Step 2 Define how to handle the response from the server by creating Ready State Handler.
  3. Step 3 Specify your request method (GET or POST), url and send to the server

Compared to how we iterate through XML elements, iterating through JSON is simpler as JSON is actually Javascript objects. We are using Javascript to get value from server, it is naturally easier to get values that we want from Javascript objects than XML collections. This is one of the reason why JSON is more favorable than XML.

Another advantage of JSON, still it's because it is Javascript, we can easily access Javascript from another website. However, reading XML from another domain is forbidden due to cross domain policy. Therefore, I think it is unfair for XML to compete with JSON in popularity.

<script>
function GetData() {
    // 1. Instantiate XHR - Start 
var xhr; if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); else if (window.ActiveXObject) xhr = new ActiveXObject("Msxml2.XMLHTTP"); else throw new Error("Ajax is not supported by your browser"); // 1. Instantiate XHR - End // 2. Handle Response from Server - Start xhr.onreadystatechange = function () { if (xhr.readyState < 4) document.getElementById('div1').innerHTML = "Loading..."; else if (xhr.readyState === 4) { if (xhr.status == 200 && xhr.status < 300) { var json = JSON.parse(xhr.responseText);reponseText returns the entire JSON file and we assign it to a javascript variable "json". document.getElementById('div1').innerHTML = json.collection.movie[0].title; get first value with "title" element } } } // 2. Handle Response from Server - End // 3. Specify your action, location and Send to the server - Start xhr.open('GET', 'http://www.ajax-tutor.com/demo/movies.json'); xhr.send(null); // 3. Specify your action, location and Send to the server - End } </script>