Home arrow JavaScript arrow Page 2 - 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 - 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.


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