spacer
home / programming / javascript / jf / column13 / 1 current pageTo page 2To page 3
[next]

ASP 3.0/.NET Developer
Jupitermedia
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume
Biz Resources
Technology Asset Management Software
Information Technology Services
ecommerce solutions
Developer News
SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear

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!

home / programming / javascript / jf / column13 / 1 current pageTo page 2To page 3
[next]



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
How to Create an Ajax Autocomplete Text Field: Part 6 · Software Engineering for Ajax · Perl Pragma Primer
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Using File Virtualization for Disaster Recovery · VoIP Security: SIP—Versatile but Vulnerable · Around the World in 80 Nodes

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

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