We have seen how XHR sends us data from server using the property "responseText". Let's us look at how "responseXML" works. First of all, let's take an XML file (movies.xml) as our example.

I'm going to use the exact same piece of code that we have seen earlier to retrieve the first movie "title" of movies.xml file.

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

What's difference now is how do we handle the response coming from server in step 2. Based on the XHR property of responseXML, we then assigned it to an object by the name of xmlDoc.

We then use getElementsByTagName to give us the collection of all elements by the value of "title".

Subsequently, we will be iterate through the collection and pick up the value that we want.

In this simple example, it is the first movie title of the collection.

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) { xmlDoc = xhr.responseXML; reponseXML returns an XML document and we assign it to xmlDoc titles = xmlDoc.getElementsByTagName("title"); get XML element collection with the content of "title" document.getElementById('div1').innerHTML = titles[0].childNodes[0].nodeValue; 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.xml'); xhr.send(null); // 3. Specify your action, location and Send to the server - End } </script>