07 - AJAX ResponseXML Example

Let’s create a new example to work with the property responseXML. First of all, we can create an XML document in the Ajax folder, with the response we want to receive from the server upon our xmlHttpRequest, I will call this document: AjaxXMLResponse.xml.

        <from>John Doe</from>
        <title>Keep this record</title>
        <description>This is the first of many XML records</description>
        <from>Gabriel J</from>
        <to>Jhon Doe</to>
        <title>Important message</title>
        <description>Please read this message</description>
        <from>John Doe</from>
        <to>Gabriel J</to>
        <title>Re: Important message</title>
        <description>Yes, I have read it!</description>

Now, let’s create a new html document called: XMLAjaxDemo.html.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>AJAX Demo</title>
        function loadAjaxReponseXML()
        var xmlHTTPRequest;
        var txtToBeWritten,record,i;
        if (window.XMLHttpRequest)
          {// Validation for Internet Explorer 7 and upo, Firefox, Chrome, etc 
          xmlHTTPRequest=new XMLHttpRequest();
          {// Web browser is Internet Explorer 5 or 6 
          xmlHTTPRequest=new ActiveXObject("Microsoft.XMLHTTP");
          if (xmlHTTPRequest.readyState==4 && xmlHTTPRequest.status==200)
            for (i=0;i<records.length;i++)
              txtToBeWritten = txtToBeWritten + records[i].childNodes[0].nodeValue + "<br>";
        <form id="form1">
            <h1>AJAX DEMO: ResponseXML<h1>
            Display record titles:
            <input type="button" id="submit" value="Click Me!" onclick="loadAjaxReponseXML()"/>
            <div id="AjaxResponseXMLHere">

In this example, we use the xmlHTTPRequest.responseXML to read the information sent by the server. Once we have this we can use regular DOM accessing javascript functions to read different tags.

Now let’s try opening the following page: http://localhost:8080/Ajax/XMLAjaxDemo.html

We should see a page like the following:

Once we click on the Click Me! button, the content from the XML file that we request (AjaxXMLResponse.xml) should be displayed. In our example we are only displaying each record’s title, but you could display all the elements if you want.

Like us on Facebook