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!
Next: The full source code of the sample AJAX application >>
More JavaScript Articles
More By Alejandro Gervasio