JavaScript
  Home arrow JavaScript arrow Page 3 - Parsing AJAX Responses with JavaScript and...
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

Parsing AJAX Responses with JavaScript and the innerHTML Property
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 6
    2007-10-30

    Table of Contents:
  • Parsing AJAX Responses with JavaScript and the innerHTML Property
  • Working with HTTP XML Request objects
  • Parsing web server responses
  • The full source code of the sample 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


    Parsing AJAX Responses with JavaScript and the innerHTML Property - Parsing web server responses


    (Page 3 of 4 )

    According to the concepts deployed in the previous section, one of the simplest way to parse a web server response with AJAX is by using a proper combination of the "responseText" and the non-standard "innerHTML" JavaScript properties.

    To understand more clearly how this works, assume that there's a basic "Users" MySQL table, which has been populated with the following data:

    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

    Okay, now that you've seen the basic data contained in the MySQL database table, I'd use the following pair of PHP classes to connect to the server, perform some basic SQL queries and fetch the corresponding result sets:

    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;

     }

    }

    As you can see, the two PHP classes above are simple to grasp, and very useful for performing the most common tasks associated with MySQL, such as establishing a connection to the server, executing different queries, handling data sets, and so forth.

    Now, having listed the definitions of the PHP classes that interact with MySQL, say that you want to build an AJAX application that displays cyclically on the browser the information of each user stored on the previous "Users" database table.

    In this case, the following PHP script will fetch one row at a time from the mentioned database table, and then send this data back to the client as plain text for further processing:

    // 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){

    echo '<h2>User Information</h2><h3>First Name</h3><p>'.$row
    ['firstname'].'</p><h3>Last Name</h3><p>'.$row
    ['lastname'].'</p><h3>Email</h3><p>'.$row
    ['email'].'</p><h3>Comments</h3><p>'.$row['comments'].'</p>';

    }

    As shown above, the previous PHP script utilizes a simple "counter" session variable to determine which database table row must be sent back to the browser to be displayed with AJAX. However, the most important thing to notice here is that the web server response is transmitted as plain text, which means that it's necessary to define in the client another JavaScript function capable of parsing this response efficiently.

    The JavaScript function responsible for parsing all the user data coming from the web server has the following signature:

    // display user data using the 'innerHTML' property

    function displayResults(userData){

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

       if(!datacont){return};

      datacont.innerHTML='';

      datacont.innerHTML=userData;

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

    }

    See how simple it is to parse a web server response sent as plain text via the popular "innerHTML" JavaScript property? I bet you do! The above "displayResults()" function simply takes the value of the "responseText" AJAX property and  populates this data into a predetermined (X)HTML container, identified as "datacontainer."

    Finally, to make this AJAX application rotate the data associated with a specific user, the function uses a JavaScript timer to send a different HTTP request to the web server every five seconds. Easy to grasp, right?

    Now that you have seen in detail how to use the neat "innerHTML" JavaScript property to parse specific web server data sent as plain text, you'll have to agree with me that the property in question is handy for performing this kind of task. Of course, the downside of using it rests on that the fact that "innerHTML" is a non-standard property, so if you're trying to develop web applications that stick to the standards, this might not be the best choice to follow.

    All right, at this stage I have shown you how to develop a simple AJAX application that displays, at a predefined time interval, information associated with some users stored on a MySQL database table. The most important thing to learn in this case is that all this data is parsed by using the "innerHTML" JavaScript property.

    However, you may want to have at your disposal the full source code of this AJAX application. Therefore, in the final section of this article I'll be listing the complete definition of each file that comprises the application.

    Click on the link below and keep reading. We're almost finished!

    More JavaScript Articles
    More By Alejandro Gervasio


       · Over the course of this initial installment of the series, the JavaScript...
     

    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 3 hosted by Hostway
    Stay green...Green IT