JavaScript
  Home arrow JavaScript arrow Page 2 - 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 - Preparing the scenario for parsing XML data


    (Page 2 of 4 )

    Definitely, a good point to start demonstrating how to parse AJAX responses that are delivered in XML format consists of rebuilding the development scenario that I created in the preceding article of the series. As you'll surely recall, I developed a basic AJAX application that was tasked with displaying cyclically on the browser some basic data about a group of hypothetical users.

    The information on the users in question was previously stored on a simple MySQL database table, whose structure looked similar to the one shown below:

    Id First Name Last Name Email Comments

    • 1 Alejandro Gervasio alejandro@domain.com MySQL is great for building a search engine
    • 2 John Williams john@domain.com PHP is a server side scripting language
    • 3 Susan Norton susan@domain.com JavaScript is good to manipulate documents
    • 4 Julie Wilson Julie@domain.com MySQL is the best open source database

    In addition, I also defined a pair of MySQL processing classes with PHP 5, which came in particularly useful for fetching the database records listed above. The respective definitions for the classes looked like this:

    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;

     }

    }

    All right, now that I have listed the complete signatures of the PHP 5 classes that I utilized for fetching the data corresponding to the previous fictional users, the last thing required to complete this development schema is simply to create a JavaScript function that allows you to send out HTTP requests via AJAX. As you might recall, this function was previously defined in the following way:

    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','plain/text; charset=UTF-
    8');

    // send http request

      xmlobj.send(null);

    }

    So far, so good. Assuming that the way that the above function works is now very familiar to you, certainly I'm not going to spend your precious time explaining what it does. Instead, considering that everything has been set up to get this AJAX application working seamlessly, in the course of the section to come I'm going to show you how to create a simple PHP 5 script which will fetch from the sample "Users" database table the respective user records that you saw previously, and then send this data back to the browser in XML format.

    Also, on the client side, I'm going to define a brand new JavaScript function. It will be responsible for parsing this database information by using the popular "responseXML" AJAX property, in this way demonstrating how to parse AJAX responses that are served in XML.

    To learn how all of these interesting tasks will be carried out, click on the link 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 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 1 hosted by Hostway
    Stay green...Green IT