Using DOM Scripting to Parse AJAX Responses with JavaScript - Listing the complete source code
(Page 4 of 4 )
In consonance with the concepts deployed in the prior section, below you can see the complete signatures of the source files that comprise this AJAX-driven application. I suggest you take a close look at it to quickly learn the approach I used to parse plain text responses with a few DOM methods.
Here are all the signatures for all the source files that I mentioned before:
(definition of ajax_sample.htm file)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />
<title>Example of responseText property (uses the DOM to fetch
user data)</title>
<script language="javascript">
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);
}
function displayResults(userData){
var datacont=document.getElementById('datacontainer');
if(!datacont){return};
var userData=userData.split('|');
if(userData.length>0){
var cont=document.getElementById('container');
if(cont){cont.parentNode.removeChild(cont)};
var div=document.createElement('div');
div.setAttribute('id','container');
for(var i=0;i<userData.length;i++){
var h3=document.createElement('h3');
var par=document.createElement('p');
h3.appendChild(document.createTextNode(userData[i].split(':')
[0]));
par.appendChild(document.createTextNode(userData[i].split(':')
[1]));
div.appendChild(h3);
div.appendChild(par);
}
datacont.appendChild(div);
}
setTimeout("sendHttpRequest
('get_user_data.php','displayResults')",5*1000);
}
// fetch data from first user when web page is loaded
window.onload=function(){
if(document.getElementById&&document.
getElementsByTagName&&document.createElement){
sendHttpRequest('get_user_data.php','displayResults');
}
}
</script>
<style type="text/css">
body{
padding:0;
margin:0;
background: #eee;
}
h1{
font: bold 14pt Arial, Helvetica, sans-serif;
color: #000;
text-align: center;
}
h2{
font: bold 12pt Arial, Helvetica, sans-serif;
color: #00f;
}
h3{
font: bold 11pt Arial, Helvetica, sans-serif;
color: #000;
}
p{
font: normal 10pt Arial, Helvetica, sans-serif;
color: #000;
}
#datacontainer{
width: 30em;
padding: 10px;
margin-left: auto;
margin-right: auto;
background: #ffc;
border: 1px solid #999;
}
</style>
</head>
<body>
<h1>Example of AJAX responseText property</h1>
<div id="datacontainer"> </div>
</body>
</html>
(definition get_user_data.php file)
<?php
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;
}
}
// 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 'First Name:'.$row['firstname'].'|Last Name:'.$row
['lastname'].'|Email:'.$row['email'].'|Comments:'.$row
['comments'];
}
?>
Above are all the source files that you need to get this sample AJAX application working seamlessly. It's extremely important to notice here how the PHP 5 script that actually fetches the database rows from the "Users" table uses a "|" delimiter to concatenate the different table fields before sending this data back to the browser to be parsed by the "displayResult()" JavaScript function that was discussed in the previous section. Quite simple, right?
A final note: as usual, you're free to modify all the code samples developed in this article, if you're interested in learning yet another approach to parse within the context of an AJAX application, the output of server-side scripts.
Final thoughts
In this second tutorial of the series I demonstrated how to use some standard DOM methods to process AJAX responses that are sent to the client in plain text, using the "responseText" property.
Nonetheless, this instructive journey has one more chapter, since I've not explained yet how to parse AJAX responses that are transmitted in XML format. As you might have guessed, this topic will be covered deeply in the last part of the series, so now you don't have any excuses to miss it!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |