How to use AJAX and XmlHttpRequest in PHP?

With Web services growing in popularity, you may occasionally find it convenient to connect an HTML presentation directly to the XML data for interim updates without reloading the page. To convert the retrieved XML data into renderable HTML content, rely on the client-side Document Object Model (DOM) to read the XML document node tree and compose HTML elements that the user sees.

You must be aware that the XmlHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0/Firefox and Netscape 7 browsers only.

To work with this article, you should have some basic PHP, MySQL and JavaScript experience. In this article, we will see how one can retrieve the Firstname and Balance values from a MySQL database using XmlHttpRequest object.

Let us first start with the database.

Creating a table in MySQL database

Add the following table (code 1) into the MySQL database. You can then add records according to your wish.

Code 1

# Table structure for table `bank`
#

CREATE TABLE `bank` (
`accountno` mediumint(9) NOT NULL default '0',
`firstname` tinytext NOT NULL,
`balance` tinytext NOT NULL,
PRIMARY KEY (`accountno`),
UNIQUE KEY `accountno_2` (`accountno`),
KEY `bank` (`accountno`)
) TYPE=MyISAM;


Anyone with even a little background of SQL would be able to understand the above code. I have populated the table with about 15 records. These records have bank account number as the unique primary key and it starts from 1001 to 1015.

Create a Form in html page

First, create a simple web page and name it as balance.html. Add three fields — accountno, Firstname and balance. Code 2 provides you with the plain HTML code for the three fields. 

Code 2

<!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>
<title>Getting Firstname and Balance using XmlHttpRequest</title>
</head>
<body>
<form action="post">
<p>
<br>
<b><font color="#800000" size="4">Checking Balance using Ajax</font></b>
<b><font color="#800000" size="4">in
PHP</font></b>
</p>
<table border="1" width="49%">
<tr>
<td width="50%"><b><font color="#000080" face="Verdana" size="3">Account
Number:</font></b></td>
<td width="50%"><input type="text" size="13" name="accountno" id="accountno" onMouseOut=="updatefirst_balance();" />
</td>
</tr>
<tr>
<td width="50%"><font size="3" face="Verdana" color="#000080"><b>First
Name:</b></font></td>
<td width="50%"><input type="text" name="firstname" id="firstname" size="23" />
</td>
</tr>
<tr>
<td width="50%"><b><font size="3" face="Verdana" color="#000080">Balance:</font></b></td>
<td width="50%"><input type="text" size="23" name="balance" id="balance" />
</td>
</tr>
</table>
<p>
</p>
</form>
</body>
</html>

JavaScript Event Handler in Html Page
After the plain html form has been created, add an onMouseOut event handler function named updatefirst_balance(). This event handler is called whenever the accountno code field loses focus.
onMouseOut==" updatefirst_balance();" 

Using the updatefirst_balance() function, you can retrieve the firstname and balance for a given account number.

Generate XmlHttpRequest object
The best way to create an XmlHttpRequest object is to use a function named getHTTPObject(). This function has precompiled directives, which make it pretty cross-browser compatible. Add the following code 3 in the balance.html page.

The code can be divided into three parts. Let us start with the lowermost portion of the code. The function getHttpObject() is a simple loop to check whether the browser supported is Internet Explorer or one from the Mozilla family.

Code 3

<script language="javascript" type="text/javascript">

function handleHttpResponse() {
if (http.readyState == 4) {

results = http.responseText.split(",");
document.getElementById('firstname').value = firstname;
document.getElementById('balance').value = balance;
}
}
}

function updatefirst_balance() {
var accountno = document.getElementById("accountno").value;
http.open("GET", url + escape(accountno), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}

function getHTTPObject() {
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>



We first specify the URL for the server-side script to be getbalance.php?param= . This URL will then have the Accountno code appended to it so that Accountno is passed as an HTTP GET parameter named param. This means that if a user types in the Accountno 1010, the resulting URL would be getbalance.php?param=1010.

Before we send the HTTP request, we specify the onreadystatechange property to be the name of our new function handleHttpResponse(). This means that every time the HTTP ready state changes, the function handleHttpResponse() is called. 

Our new function handleHttpResponse() sits there waiting to be called and when it does get called, it checks to see if the readState is equal to 4. If it is equal to 4, this means that the request is complete. Since the request is complete, the program can grab the response text (responseText), unpack it and set the firstname and balance form fields to the returned values.

Getting Account Number from the Database
Now we will write a simple query to retrieve Firstname and Balance from the table ‘bank’. Refer code 4.

Code 4

<?php
function db_connect() {
$database_name = 'ajax'; // Set this to your Database Name
$database_username = 'test'; // Set this to your MySQL username
$database_password = 'test'; // Set this to your MySQL password
$result = mysql_pconnect('localhost',$database_username, $database_password); 
if (!$result) return false;
if (!mysql_select_db($database_name)) return false;
return $result;
}

$conn = db_connect(); // Connect to database
if ($conn) 

{
$accountno = $_GET['param']; // The parameter passed to us
$query = "select * from bank where accountno = '$accountno'";
$result = mysql_query($query,$conn);
$count = mysql_num_rows($result);
if ($count > 0) 
{
$firstname = mysql_result($result,0,'firstname');
$balance = mysql_result($result,0,'balance');
}
}

if (isset($firstname) && isset($balance)) 

$return_value = $firstname . "," . $surname . "," . "balance";
}

else 

$return_value = "invalid".",".$_GET['param']; // Include Zip for debugging purposes
}
echo $return_value; 
// This will become the response value for the XMLHttpRequest object
?>


Once you have changed the code to reflect your database settings, a good way to test this file is to use your web browser and launch its URL, complete with a query string containing an account number. The following URL will reveal the output for firstname and balance, http://www.developeriq.com/ajax/getbalance.php?param=1010.

We should now add the XML code. Since the query returns results are simple, the need to use XML has not arisen. However, if you have more records and want to search for a particular value then it will be time-consuming. That is the reason why we use XML. Modify the following line in the above code as shown in code 5.

Code 5

if (isset($firstname) && isset($balance)) 

// $return_value = $firstname . "," . $surname . "," . "balance";

$return_value = '<?xml version="1.0" standalone="yes"?><accountno><firstname>'.$firstname.'</firstname>
<balance>'.$balance.'</balance></accountno>';
}

else 

$return_value = "invalid".",".$_GET['param']; // Include Zip for debugging purposes
}

header('Content-Type: text/xml'); 
echo $return_value; 
// This will become the response value for the XMLHttpRequest object


In the above code, the JavaScript XmlHttpRequest object will not recognize the data as XML without this header. Data will be retrieved in XML format.

On the client-side, we switch to using the responseXML property rather than the responseText property to retrieve output from the server script. The responseXML property gives us an XMLDocument object that we can pass through to get our Firstname and Balance. Check out code 6.

Code 6

<script language="javascript" type="text/javascript">
var url = "getbalance.php?param="; // The server-side script
function handleHttpResponse() {
if (http.readyState == 4) {
if (http.responseText.indexOf('invalid') == -1) {
// Use the XML DOM to unpack the city and state data 
var xmlDocument = http.responseXML;


var firstname = xmlDocument.getElementsByTagName('firstname').item(0).firstChild.data;
var balance = xmlDocument.getElementsByTagName('balance').item(0).firstChild.data;
document.getElementById('firstname').value = firstname;
document.getElementById('balance').value = balance;
isWorking = false;
}
}
}

var isWorking = false;
function updatefirst_balance() {
if (!isWorking && http) {
var accountno = document.getElementById("accountno").value;
http.open("GET", url + escape(accountno), true);
http.onreadystatechange = handleHttpResponse;
isWorking = true;
http.send(null);
}
}
</script>


The power of XmlHttpRequest object can only be understood when the size of the database grows to a few hundred thousand records. The program will still function efficiently and really fast. 

If you are a PHP developer and are looking at resolving the slackness in database calls, look at Ajax and get your applications to turbo charge.




Added on January 17, 2007 Comment

Comments

Post a comment

Your name:

Comment: