Parsing AJAX Responses with JavaScript and the innerHTML Property - The full source code of the sample AJAX application
(Page 4 of 4 )
As I stated in the earlier section, here is the entire source code of this sample AJAX application. It uses the "innerHTML" JavaScript property to parse user data coming from the sample "Users" MySQL database table that you saw previously:
(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 innerHTML
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','plain/text; charset=UTF-
8');
// send http request
xmlobj.send(null);
}
// 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 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){
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 usual with my articles on web development, you're completely free to tweak all the code samples shown in this tutorial. In this way you can become comfortable with using the non-standard "innerHTML" property to parse server responses that are sent as plain text.
Final thoughts
In this first article of the series you hopefully learned how to use the "innerHTML" JavaScript property to parse different web server responses within AJAX-based applications. Nonetheless, the down side to using this property is that it's not considered standard by the W3 Consortium.
Therefore, in the next part of the series, I'll show you how to utilize the functionality of the DOM (instead of the previous "innerHTML" property) to parse plain text web server responses from inside a concrete AJAX application.
Now that you've been warned, I hope to see you there!
| 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. |