JavaScript
  Home arrow JavaScript arrow Page 3 - Processing XML Data from AJAX Responses wi...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Moblin 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Processing XML Data from AJAX Responses with JavaScript
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2007-11-13

    Table of Contents:
  • Processing XML Data from AJAX Responses with JavaScript
  • Preparing the scenario for parsing XML data
  • Using the responseXML property
  • Assembling the different modules of the AJAX application

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Processing XML Data from AJAX Responses with JavaScript - Using the responseXML property


    (Page 3 of 4 )

    As I stated in the previous section, I'm going to build a short PHP 5 script, which will have the capacity to fetch from MySQL, the database rows that you saw previously, which will finally be sent to the browser in XML format.

    Having explained how this simple script will work, below I included its corresponding signature, so have a look at it, please:

    // connect to MySQL

    $db=new MySQL(array
    ('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'database'));

      session_start();

    !$_SESSION['counter']||$_SESSION['counter']>3?$_SESSION
    ['counter']=1:$_SESSION['counter']++;

      $id=$_SESSION['counter'];

    // run query

    $result=$db->query("SELECT firstname,lastname,email,comments FROM
    users WHERE id='$id'");

    // send user data back to main page

      $row=$result->fetchRow();

       if($result->countRows()==1){

        header('Content-Type: text/xml; charset=iso-8859-1');

      echo '<?xml version="1.0" encoding="iso-8859-1"?>';

      echo '<userdata>';

       echo '<firstname>'.$row['firstname'].'</firstname>';

      echo '<lastname>'.$row['lastname'].'</lastname>';

      echo '<email>'.$row['email'].'</email>';

      echo '<comments>'.$row['comments'].'</comments>';

      echo '</userdata>';

    }

    Definitely, after studying the above PHP 5 script, you'll have to agree with me that things are getting really interesting at this point. As you can see, the script in question retrieves one database record at a time, based upon a simple session mechanism, and then echoes this data in basic XML format. Quite easy to grasp, right?

    The purpose in doing this is to send to the client all the data fetched from the respective "Users" MySQL database table in a format (in this case, as XML) that will be extremely easy to parse, by utilizing some DOM scripting.

    To prove the veracity of this concept, below I defined a brand new JavaScript function, which takes up the XML data sent by the previous script, and then displays neatly on the browser all the information about a user.

    The signature of the JavaScript function is as follows:

    function displayResults(userData){

     var datacont=document.getElementById('datacontainer');

      if(!datacont){return};

     var firstName=userData.getElementsByTagName('firstname')
    [0].firstChild.nodeValue;

     var lastName=userData.getElementsByTagName('lastname')
    [0].firstChild.nodeValue;

     var email=userData.getElementsByTagName('email')
    [0].firstChild.nodeValue;

     var comments=userData.getElementsByTagName('comments')
    [0].firstChild.nodeValue;

     var fnh3=document.createElement('h3');

     var lnh3=document.createElement('h3');

     var emh3=document.createElement('h3');

     var coh3=document.createElement('h3');

     var fnpar=document.createElement('p');

     var lnpar=document.createElement('p');

     var empar=document.createElement('p');

     var copar=document.createElement('p');

     var div=document.createElement('div');

     var cont=document.getElementById('container');

      if(cont){cont.parentNode.removeChild(cont)};

       div.setAttribute('id','container');

     fnh3.appendChild(document.createTextNode('First Name'));

     fnpar.appendChild(document.createTextNode(firstName));

     lnh3.appendChild(document.createTextNode('Last Name'));

     lnpar.appendChild(document.createTextNode(lastName));

     emh3.appendChild(document.createTextNode('Email'));

     empar.appendChild(document.createTextNode(email));

     coh3.appendChild(document.createTextNode('Comments'));

     copar.appendChild(document.createTextNode(comments));

      div.appendChild(fnh3);

      div.appendChild(fnpar);

      div.appendChild(lnh3);

      div.appendChild(lnpar);

      div.appendChild(emh3);

      div.appendChild(empar);

      div.appendChild(coh3);

      div.appendChild(copar);

    datacont.appendChild(div);

    setTimeout("sendHttpRequest
    ('get_user_data.php','displayResults',true)",5*1000);

    }

    As you can see, the prior "displayResults()" JavaScript function performs a few simple tasks to parse the user data that comes from the web server. In this case, this function utilizes a combination of the "responseXML" AJAX property and some common DOM methods for displaying on the browser the pertinent information for a specific user, in this way implementing a fully standard approach for processing AJAX responses.

    It's fair to notice here that the previous JavaScript function may seem rather complex at first sight, but if you study its source code in more detail, you'll realize that it uses a few basic DOM methods to manipulate the web document tree and display the pertinent user data in the client.

    Well, at this stage hopefully you grasped the logic that stands behind parsing AJAX responses that are served in XML format. As you saw earlier, this process is quite straightforward and can be performed easily with the assistance of the neat "responseXML" property.

    Thus, considering the fact that you may want to see the complete source code corresponding to this sample AJAX application, in the last section of this tutorial I'll be listing this code. Having it all in one place will make it easy for you to copy it and paste it into your preferred code editor for further improvements.

    To see the entire source code of this AJAX application, click on the link shown below and keep reading.

    More JavaScript Articles
    More By Alejandro Gervasio


       · During this last chapter of the series, you’ll learn how to develop a simple –yet...
     

    JAVASCRIPT ARTICLES

    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget
    - Ajax Hack for Entering Information Without R...
    - EXT JS 2.1 Overview
    - Using the Style Object for Zebra Tables with...
    - Binary Searching
    - An Improved Approach to Building Zebra Tables






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway
    Stay green...Green IT