Processing XML Data from AJAX Responses with JavaScript - Assembling the different modules of the AJAX application
(Page 4 of 4 )
Indeed, the best way to finish this article is by listing the complete source files that comprise this sample AJAX application. In this way you can see more clearly how each of these files interact with each other.
That being said, here are the full signatures for the two files that compose the mentioned AJAX application:
(definition of sample_ajax.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 responseXML property</title>
<script language="javascript">
// send 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','text/xml; charset=UTF-8');
// send http request
xmlobj.send(null);
}
// display user data using the responseXML property
function displayResults(userData){
var datacont=document.getElementById('datacontainer');
if(!datacont){return};
var firstName=userData.getElementsByTagName('firstname')
[0].firstChild.nodeValue;
var lastName=userData.getElementsByTagName('lastname')
[0].firstChild.nodeValue;
var email=userData.getElementsByTagName('email')
[0].firstChild.nodeValue;
var comments=userData.getElementsByTagName('comments')
[0].firstChild.nodeValue;
var fnh3=document.createElement('h3');
var lnh3=document.createElement('h3');
var emh3=document.createElement('h3');
var coh3=document.createElement('h3');
var fnpar=document.createElement('p');
var lnpar=document.createElement('p');
var empar=document.createElement('p');
var copar=document.createElement('p');
var div=document.createElement('div');
var cont=document.getElementById('container');
if(cont){cont.parentNode.removeChild(cont)};
div.setAttribute('id','container');
fnh3.appendChild(document.createTextNode('First Name'));
fnpar.appendChild(document.createTextNode(firstName));
lnh3.appendChild(document.createTextNode('Last Name'));
lnpar.appendChild(document.createTextNode(lastName));
emh3.appendChild(document.createTextNode('Email'));
empar.appendChild(document.createTextNode(email));
coh3.appendChild(document.createTextNode('Comments'));
copar.appendChild(document.createTextNode(comments));
div.appendChild(fnh3);
div.appendChild(fnpar);
div.appendChild(lnh3);
div.appendChild(lnpar);
div.appendChild(emh3);
div.appendChild(empar);
div.appendChild(coh3);
div.appendChild(copar);
datacont.appendChild(div);
setTimeout("sendHttpRequest
('get_user_data.php','displayResults',true)",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',true);
}
}
</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 responseXML property</h1>
<div id="datacontainer"> </div>
</body>
</html>
(definition of 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){
header('Content-Type: text/xml; charset=iso-8859-1');
echo '<?xml version="1.0" encoding="iso-8859-1"?>';
echo '<userdata>';
echo '<firstname>'.$row['firstname'].'</firstname>';
echo '<lastname>'.$row['lastname'].'</lastname>';
echo '<email>'.$row['email'].'</email>';
echo '<comments>'.$row['comments'].'</comments>';
echo '</userdata>';
}
?>
That's all for the moment. As I said before, you're completely free to introduce your own modifications to all the code samples included in this article, so you can be better prepared to implement different approaches for parsing AJAX responses. Happy coding!
Final thoughts
It's hard to believe, but this is actually the end of the series. Hopefully, this group of tutorials will be quite useful to you for demonstrating how to implement different methods for parsing AJAX responses with JavaScript, whether these ones are served as plain text or in XML format.
See you in the next web development tutorial!
| 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. |