Using DOM Scripting to Parse AJAX Responses with JavaScript - Fetching some database records with AJAX
(Page 2 of 4 )
In order to demonstrate how to use the DOM for parsing a web server response sent in plain text from inside the content of an AJAX application, first I'm going to recreate the development scenario that I used in the first article of the series.
As you'll probably recall, I created a sample "Users" MySQL database table, which was previously populated with a few simple records. Then, I defined a pair of MySQL processing classes in PHP 5, which came in handy for retrieving these records and sending them back to the client in plain text.
The interaction between the classes was performed via AJAX. Here's the definition of the JavaScript function that I used to trigger the JavaScript-based 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','plain/text; charset=UTF-
8');
// send http request
xmlobj.send(null);
}
Assuming that the signature of the above "sendHttpRequest()" JavaScript function is very familiar to you at this time, the next step consists of listing the corresponding definitions of the PHP 5 classes that I defined to interact with MySQL.
Here's how this pair of MySQL processing classes looked originally:
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 you've recalled how the previous MySQL handling classes worked, the last thing that I'm going to do in this section will be listing the structure of the sample "Users" database table, whose rows were displayed at a predefined time interval on the browser, by using an AJAX-based HTTP request.
Basically, this database table was defined like this:
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
So far, so good, right? At this point I've recreated the development scenario that I showed you in the first article of the series. So what's next? Well, basically I'll keep the logic of this AJAX application nearly the same, which implies that the application will be tasked with displaying the database rows listed previously in a predefined sequence, as you learned earlier.
Here, however, is where the difference comes in: I'm going to define a brand new JavaScript function, which will be responsible for parsing the data coming from the web server by using only the DOM, instead of utilizing the non-standard "innerHTML" JavaScript property. By doing this, you'll hopefully learn how to implement a standard approach for parsing database information fetched via an AJAX-based request.
To see how this brand new JavaScript function will be defined, you'll have to visit the following section and keep reading. It's just one click away.
Next: Using DOM scripting to parse plain text responses with AJAX >>
More JavaScript Articles
More By Alejandro Gervasio