Home arrow JavaScript arrow Page 3 - Processing XML Data from AJAX Responses with JavaScript
JAVASCRIPT

Processing XML Data from AJAX Responses with JavaScript


Developing AJAX-driven applications can be an educational experience, particularly for those web developers who are taking their first steps into this exciting area. However, on the other hand, it can also be hard, specifically when it comes to deciding which output format should be used for delivering the results of AJAX-based http requests to end users. This article offers one sensible approach.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 4
November 13, 2007
TABLE OF CONTENTS:
  1. · Processing XML Data from AJAX Responses with JavaScript
  2. · Preparing the scenario for parsing XML data
  3. · Using the responseXML property
  4. · Assembling the different modules of the AJAX application

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

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.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- More Top jQuery Tutorials for Beginners
- More Top jQuery Plugins for Menus
- Top jQuery Tutorials for Beginners
- New UI Framework and SDK for JavaScript Rele...
- JavaScript OpenPGP Tool, Node.js 0.6.3 Avail...
- Yahoo Releases Cocktails Language and Develo...
- Customizing jQuery Slideshows: Dynamic Contr...
- Customizing jQuery Slideshows: the animate()...
- Customizing jQuery Slideshows: slideUp() and...
- Customizing jQuery Slideshows: hide() and sh...
- Web Workers: Performing Calculations in Para...
- More Top JavaScript Frameworks and Libraries
- More Dynamic jQuery Styling Techniques
- The Top JavaScript Libraries
- The Top JavaScript Frameworks

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials