How to Develop Web Applications with Ajax: Pt. 2 | WebReference

How to Develop Web Applications with Ajax: Pt. 2

current pageTo page 2To page 3
[next]

How to Develop Web Applications with Ajax: Pt. 2

By Jonathan Fenocchi

In part one of this series, we discussed how to retrieve remote data from an XML file via JavaScript. In this article, we'll learn how to process that data in a more complex manner. As an example, we'll take groups of XML data, separate individual segments of that data and display those segments in different ways, depending on how they're identified.

This article builds on the example code used in the previous article, so if you don't understand the code we start with here, you may want to go back and read it.

Let's Begin

Let's begin with our first step: forming the XML. We want to write an XML document that groups sets of data to be processed by JavaScript, so we'll group some nodes and sub-nodes (or, elements and sub-elements) together. In the example, we'll use the names of some household pets:

    <?xml version="1.0" encoding="UTF-8"?>
    <data>
      <pets>
       <pet>Cat</pet>
       <pet>Dog</pet>
       <pet>Fish</pet>
      </pets>
    </data>

Above, we have the XML declaration (states that the document is an XML 1.0 document, encoded with the UTF-8 character set standard), a root element (<data>) that groups all underlying elements together, a <pets> element that groups all pets together, and then a <pet> node for each pet. To specify what type of animal each pet is, we put a text node within the <pet> elements: Cat, Dog, and Fish.

We’re going to build upon the HTML document I built in the last lesson and expand it to make it more flexible with the new XML file here:

     <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
      "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en" dir="ltr">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Developing Web Applications with Ajax - Example</title>
        <script type="text/javascript"><!--
        function ajaxRead(file){
          var xmlObj = null;
          if(window.XMLHttpRequest){
              xmlObj = new XMLHttpRequest();
          } else if(window.ActiveXObject){
              xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
          } else {
              return;
          }
          xmlObj.onreadystatechange = function(){
            if(xmlObj.readyState == 4){
              processXML(xmlObj.responseXML);
            }
          }
          xmlObj.open ('GET', file, true);
          xmlObj.send ('');
        }
        function processXML(obj){
          var dataArray = obj.getElementsByTagName('pet');
          var dataArrayLen = dataArray.length;
          var insertData = '<table style="width:150px; border: solid 1px #000"><tr><th>'
            + 'Pets</th></tr>';
          for (var i=0; i<dataArrayLen; i++){
              insertData += '<tr><td>' + dataArray[i].firstChild.data + '</td></tr>';
          }
          insertData += '</table>';
          document.getElementById ('dataArea').innerHTML = insertData;
        }
        //--></script>
      </head>
      <body>
        <h1>Developing Web Applications with Ajax</h1>
        <p>This page demonstrates the use of Asynchronous Javascript and XML (Ajax) technology to
      update a web page's content by reading from a remote file dynamically
    -- no page reloading
      is required. Note that this operation does not work for users without JavaScript enabled.</p>
        <p>This page particularly demonstrates the retrieval and processing of grouped sets of XML data.
        The data retrieved will be output into a tabular format below.
    <a href="#" onclick="ajaxRead('data.xml'); return false">See the demonstration</a>.</p>
        <div id="dataArea"></div>
      </body>
    </html>

You’ll notice we’re calling the function in the same way as last time, via a link, and we’re putting data into a DIV (this time named “dataArea”). The ajaxRead() function is similar, except for one difference: the onreadystatechange function. Let’s have a look at that first:

         xmlObj.onreadystatechange = function(){
          if(xmlObj.readyState == 4){
              processXML(xmlObj.responseXML);
         }
    }

We no longer have the updateObj function. Instead, we invoke a new function called processXML(). This function will take the XML document itself (which the ajaxRead function retrieved) and process it. (The “XML document itself” to which I refer is the parameter “xmlObj.responseXML.”)

Let’s analyze that processXML function now. Here it is again:

        function processXML(obj){
          var dataArray = obj.getElementsByTagName('pet');
          var dataArrayLen = dataArray.length;
          var insertData = '<table style="width:150px; border: solid 1px #000"><tr><th>'
          + 'Pets</th></tr>';
          for (var i=0; i<dataArrayLen; i++){
              insertData += '<tr><td>' + dataArray[i].firstChild.data + '</td></tr>';
         }
         insertData += '</table>';
        document.getElementById ('dataArea').innerHTML = insertData;
    }

First, a few variables are defined. “dataArray” becomes an array of all the <pet> nodes (not the node data, just the nodes). “dataArrayLen” is just the length of that array, used for our for loop. “insertData” is the beginning HTML for a table.

Our next step is to loop through all of the <pet> elements (by using the “dataArray” variable) and add that data to the insertData variable. Here we create a table row, insert a table data node inside it, insert the text each <pet> element contains into the table data node, and append all that into the “insertData” variable. Thus, each time the loop continues, the insertData variable has a new row of data containing the name of one of the three pets.

Following the appendage of new data rows, we insert a closing “</table>” tag into the “insertData” variable. This completes the table, and we’ve got one task left before closing this operation: we need to put this table on the page. Fortunately, thanks to the innerHTML property, this is easy. We fetch the ‘dataArea’ DIV via document.getElementById() and insert the “insertData” variable’s HTML into it. This makes the table appear!

current pageTo page 2To page 3
[next]

Created: March 27, 2003
Revised: October 7, 2005

URL: http://webreference.com/programming/javascript/jf/column13/1