Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Receiving XML from the Server

var xml = XMLHttp.responseXML;

The responseText property works well for a limited amount of unstructured data. However, a more elegant approach for using complex, structured data within an AJAX application promises to be the responseXML property. When accessing this property, you get the response of the HTTP request as a JavaScript XML DOM object—of course, only if the server returns valid XML; otherwise, you get null.

Accessing the details of the XML object is quite similar to accessing DOM elements from JavaScript. For this phrase, the following sample XML file will be used:

Sample XML Data (phrasebook.xml)

  <book pubdate="2006">
    <title>JavaScript Phrasebook</title>
    <publisher>Sams Publishing</publisher>

For the web browsers to read in this XML (Internet Explorer especially is very strict in that regard), the correct MIME type must be sent to the client: text/xml. If you are using Apache, the following configuration in mime.types should do the trick, but is already there by default:


On Internet Information Services, you can configure the MIME types in the administration console (Start, Run, inetmgr). Alternatively, let a server-side script serve the file with the correct MIME type; generally this is a must if you are using server-side technology to generate the XML:

Setting the Correct Response MIME Type (phrasebook.xml.php)

  header('Content-type: text/xml');

Then, the following code accesses the information in the XML file, using the DOM structure and methods like getElementsByTagName() and getAttribute(). Figure 11.2 shows the result.

Extracting Information from the HTTP Response (xmlhttpxml.html)

<script language="JavaScript"
  type="text/javascript" src="xmlhttp.js"></script>
<script language="JavaScript"
var XMLHttp = getXMLHttp();
XMLHttp.open("GET", "phrasebook.xml");
XMLHttp.onreadystatechange = handlerFunction;

function handlerFunction() {
  if (XMLHttp.readyState == 4) {
    var xml = XMLHttp.responseXML;
    var book = xml.getElementsByTagName("book")[0];
    var pubdate = book.getAttribute("pubdate");
    var title, publisher;
    for (var i=0; i<book.childNodes.length; i++) {
      if (book.childNodes[i].nodeName == "title") {
        title = book.childNodes[i].firstChild.nodeValue;
      } else if (book.childNodes[i].nodeName == "publisher") {
        publisher = book.childNodes[i].firstChild.nodeValue;
    window.alert(title + " by " + publisher +
                 " (" + pubdate + ")");
Figure 11.2

Figure 11.2 The data from the XML file.

  • + Share This
  • 🔖 Save To Your Account