JavaScript
  Home arrow JavaScript arrow Page 4 - 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  
Mobile Linux 
App Generation ROI 
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 - Assembling the different modules of the AJAX application


    (Page 4 of 4 )

    Indeed, the best way to finish this article is by listing the complete source files that comprise this sample AJAX application. In this way you can see more clearly how each of these files interact with each other.

    That being said, here are the full signatures for the two files that compose the mentioned AJAX application:

    (definition of sample_ajax.htm file)


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />

    <title>Example of responseXML property</title>

    <script language="javascript">

    // send http requests

    function sendHttpRequest(url,callbackFunc,respXml){

      var xmlobj=null;

       try{

        xmlobj=new XMLHttpRequest();

    }

    catch(e){

      try{

       xmlobj=new ActiveXObject("Microsoft.XMLHTTP");

    }

      catch(e){

       alert('AJAX is not supported by your browser!');

      return false;

     }

    }

    xmlobj.onreadystatechange=function(){

      if(xmlobj.readyState==4){

      if(xmlobj.status==200){

    respXml?eval(callbackFunc+'(xmlobj.responseXML)'):eval
    (callbackFunc+'(xmlobj.responseText)');

      }

     }

    }

    // open socket connection

      xmlobj.open('GET',url,true);

    // send http header

    xmlobj.setRequestHeader('Content-Type','text/xml; charset=UTF-8');

    // send http request

      xmlobj.send(null);

    }

    // display user data using the responseXML property

     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);

    }

    // fetch data from first user when web page is loaded

    window.onload=function(){

    if(document.getElementById&&document.
    getElementsByTagName&&document.createElement){

    sendHttpRequest('get_user_data.php','displayResults',true);

     }

    }

    </script>

    <style type="text/css">

    body{

      padding:0;

      margin:0;

      background: #eee;

    }

    h1{

      font: bold 14pt Arial, Helvetica, sans-serif;

      color: #000;

      text-align: center;

    }

    h2{

      font: bold 12pt Arial, Helvetica, sans-serif;

      color: #00f;

    }

    h3{

      font: bold 11pt Arial, Helvetica, sans-serif;

      color: #000;

    }

    p{

      font: normal 10pt Arial, Helvetica, sans-serif;

      color: #000;

    }

      #datacontainer{

       width: 30em;

       padding: 10px;

       margin-left: auto;

       margin-right: auto;

       background: #ffc;

       border: 1px solid #999;

    }

    </style>

    </head>

    <body>

    <h1>Example of AJAX responseXML property</h1>

    <div id="datacontainer">&nbsp;</div>

    </body>

    </html>

    (definition of get_user_data.php file)

    <?php

    class MySQL{

      private $host;

      private $user;

      private $password;

      private $database;

      private $conId;

    // constructor

    function __construct($options=array()){

      if(!is_array($options)){

       throw new Exception('Connection options must be an array');

    }

    foreach($options as $option=>$value){

      if(empty($option)){

       throw new Exception('Connection parameter cannot be empty');

    }

      $this->{$option}=$value;

    }

      $this->connectDb();

    }

    // private 'connectDb()' method

    private function connectDb(){

    if(!$this->conId=mysql_connect($this->host,$this->user,$this-
    >password)){

        throw new Exception('Error connecting to MySQL');

    }

      if(!mysql_select_db($this->database,$this->conId)){

       throw new Exception('Error selecting database');

     }

    }

    // public 'query()' method

    public function query($sql){

      if(!$result=mysql_query($sql)){

    throw new Exception('Error running query '.$sql.' '.mysql_error());

     }

      return new Result($this,$result);

     }

    }

    class Result{

      private $mysql;

      private $result;

    // constructor

    public function __construct($mysql,$result){

      $this->mysql=$mysql;

      $this->result=$result;

    }

    // public 'fetch()' method

    public function fetchRow(){

      return mysql_fetch_array($this->result,MYSQL_ASSOC);

    }

    // public 'count()' method

    public function countRows(){

      if(!$rows=mysql_num_rows($this->result)){

       throw new Exception('Error counting rows');

    }

      return $rows;

    }

    // public 'get_insertId()' method

    public function getInsertId(){

      if(!$insId=mysql_insert_id($this->mysql->conId)){

       throw new Exception('Error getting insert ID');

    }

      return $insId;

    }

    // public 'seek()' method

    public function seekRow($row=0){

      if(!is_int($row)&&$row<0){

       throw new Exception('Invalid row parameter');

    }

      if(!$row=mysql_data_seek($this->mysql->conId,$row)){

       throw new Exception('Error seeking row');

    }

      return $row;

    }

    // public 'getAffectedRows()' method

    public function getAffectedRows(){

      if(!$rows=mysql_affected_rows($this->mysql->conId)){

       throw new Exception('Error counting affected rows');

    }

      return $rows;

     }

    }

    // 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>';

    }

    ?>

    That's all for the moment. As I said before, you're completely free to introduce your own modifications to all the code samples included in this article, so you can be better prepared to implement different approaches for parsing AJAX responses. Happy coding!

    Final thoughts

    It's hard to believe, but this is actually the end of the series. Hopefully, this group of tutorials will be quite useful to you for demonstrating how to implement different methods for parsing AJAX responses with JavaScript, whether these ones are served as plain text or in XML format.

    See you in the next web development tutorial!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - 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






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