beta it republik » Articles

Articles

Untitled Document
Thursday, 26 June 2008 | Article

Building a Simple AJAX Application

If you are anything like me, you have probably heard a lot about AJAX lately, and you are wondering what the fuss is about. AJAX can be a bit daunting for those used to doing things the old-fashioned, pre-Web 2.0 way. This article is a gentle introduction.


Introduction
If you are anything like me, you have probably heard a lot about AJAX lately, and you are wondering what the fuss is about. You are probably even thinking that AJAX is just one more hype-filled technology that really does not matter, and that if you ignore it long enough, it will blow over.

I am not too sure about AJAX’s longevity, but I am sure of one thing—any time we deliver AJAX functionality to the customer, they go crazy over it. They love how the AJAX approach makes web applications more like desktop applications. They love how responsive things become with AJAX, and that data seems to magically change within the browser without the whole page loading.

So I decided to make this article about learning AJAX. As with learning most new things, I tend to start slow and small, because too much information about AJAX can be a bit bewildering, particularly if you are used to the standard way of querying for data.

So what is AJAX?
AJAX is a term coined by Jesse James Garrett of Adaptive Path. AJAX stands for Asynchronous JavaScript and XML. Let us break that whole string of words down. Asynchronous, as in your code won’t run the way you do it now, which plods along on a linear path. Right now, you write a form that posts to a PHP form handler, which then runs a query, whose results are posted to a results page. If you want to see a new result set, you have to fill in the form and post it again.

Not so with AJAX. The key to the entire AJAX process is asynchronous activity. I will teach you how to create a JavaScript function that will query your backend PHP process in asynchronous mode, and then listens for a response when the server is ready to give it. Only after a response happens does anything change on the page.

How do these changes get effected? JavaScript. Stop groaning. I know you are doing the PHP thing and aren’t too found of JavaScript, but all you need to know about JavaScript is fairly straightforward. In fact, a lot of what AJAX requires is familiarity with the Document Object Model (DOM), because what we are essentially doing is reading values from a form, and then writing results to a uniquely identified DIV (<div>).

What about the XML part? Well, it is technically not XML, but XMLHTTPRequest. However, because you can involve XML data and you sometimes use ActiveX objects (for Internet Explorer) I shortened it to XML. The idea is to use structured data or a structured request channel to communicate with the backend process.

That’s all a bit daunting, I know. The best way to tackle AJAX is to get right in there and code. In this article, I am going to do just that. We are going to learn how to write a simple form that queries an XML file containing customer data. The form will allow users to enter a ZIP code. The results set will be customer IDs and names that match that ZIP code.

Building the Search Form
The first thing we want to tackle is the form. We are going to build the form first, then add all the AJAX stuff. Once we have worked on all the familiar stuff, you will ‘get it’ when we add the AJAX code. Our form is very simple, just one text input field for ZIP—see Listing 1.

Listing 1
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01
Transitional//EN”>
<html>
<head>
<title>First AJAX App</title>
<meta http-equiv=”Content-Type” content=”text/html;
charset=utf-8”>
</head>
<body>
<form>
<p><label for=’zip’>Enter customer zip and click anywhere on the
screen</label>
<input type=’text’ name=’zip’ id=’zip’ size=’10’ maxlength=’15’/></
p>
</form>
<div id=”resultset” style=”height:150px;overfl ow:auto;”></div>
</body>
</html>


Note that, after the form, I have added a DIV whose ID is resultset. The idea is whenever the user enters a ZIP code and clicks anywhere on the screen, this particular DIV is updated with results.

Before we get any deeper, let us look at our XML file and the PHP file that would normally process that XML file [if we were doing a normal form POST].

Our Customer XML File
Our customer data is stored in a file called customers.xml (see Listing 2). I chose to store the data in an XML file only because I thought it was appropriate; you can store the date in a MySQL table, a flat file, or anything else—it does not really matter to AJAX.

For simplicity sake, I have kept the customers.xml file short and sweet. Note that each customer has a customerid, firstname, lastname, and zip element.

Listing 2
<?xml version=”1.0” encoding=”utf-8”?>
<customers>
<customer>
<customerid>123>/customerid>
<firstname>Tom>/firstname>
<lastname>Smith>/lastname>
<zip>78727>/zip>
</customer>
<customer>
<customerid>456</customerid>
<firstname>Jane</firstname>
<lastname>Smith</lastname>
<zip>78727</zip>
</customer>
<customer>
<customerid>789</customerid>
<firstname>Tom</firstname>
<lastname>Jones</lastname>
<zip>78711</zip>
</customer>
<customer>
<customerid>144</customerid>
<firstname>June</firstname>
<lastname>Jones</lastname>
<zip>78321</zip>
</customer>
<customer>
<customerid>143</customerid>
<firstname>Joan</firstname>
<lastname>Jones</lastname>
<zip>78314</zip>
</customer>
</customers>


Next, let us work on a PHP file that parses this XML file.

The Lookup PHP File
AJAX does not absolve us from the use of PHP or other middleware language. We still need to get the data. The only thing different about AJAX is how that data is displayed, and to a large extent, how much the displayed page in the browser changes. As you will see later in the article, data that is pulled out and displayed with AJAX only changes a small part of the browser’s display area.

I created a lookup.php file, in which I accept a zip code and use that zip code to run a search on my customers.xml file. Listing 3 shows the file in its entirety.

Listing 3
<?php
//lookup customer information by sorting with incoming ZIP
code
$customers = simplexml_load_file(“customers.xml”);
$returnLine = ‘’;
if (ereg(“^[0-9]+$”,$_GET[‘zip’])){
foreach ($customers->customer as $c){
$xzip = (string)$c->zip;
if (preg_match(“/^”.$_GET[‘zip’].”/”,$xzip)){
$returnLine .=$c->customerid . “: “.$c->firstname . “
“ . $c->lastname .”<br/>”;
}//end if ((string)$c->zip == $_POST[‘zip’])
}//end foreach ($customers->customer as $c)
if (strlen($returnLine)){
echo $returnLine;
} else {
echo ‘no customers found for ‘. $_GET[‘zip’].’!’;
}//end if (strlen($returnLine))
} else {
echo ‘invalid zip!’;
}//end if (ereg(“^[0-9]+$”,$_GET[‘zip’]))


I have used SimpleXML to create a $customers object tree of the customers.xml file. Also, I use a regular expression to ensure the incoming zip code is all numeric. Note that the incoming ZIP code arrives via a GET variable.

This is where most PHP developers get hung up on AJAX. When you are working with AJAX, you do not use the form submit process to get your data. Instead, use a JavaScript function that (1) creates a request object that works asynchronously to (2)send requests, (3) waits for a response, and (4) updates the page.

In the PHP code, all we are doing is looping through the $customers object tree looking for customer ZIP codes that match the incoming ZIP code entered by the user. Note that I am using preg_match() so that anyone entering 787 (for example) will get all records whose zip codes begin with those three numbers.

If we find a match, we return customerid, firstname, and lastname node values, concatenating them to a variable named $returnLine. I have also placed various else branches throughout to catch various errors, in case of an invalid zip code or no matches on a particular zip code.

To review: so far we have talked about nothing new. I have built a form, an XML file, and a simple PHP file that extracts data from that file. In fact, all I have done at this point, to have a working form, is set action to lookup.php and method to GET to be able to echo out results. However, what I want to do is display results dynamically on the same page with the form. For that, we need AJAX.

Adding AJAX to our Form
We left the form without an action or a method. In fact, I am going to leave the form exactly like that. Instead of using a ‘submit’ button, I am going to use an onChange event handler in the zip code field, which will kick off the entire AJAX-driven search process. To get started, let us add the onChange event handler to the zip code field:

<input type=’text’ name=’zip’ id=’zip’ size=’10’ maxlength=’15’ onChange=’getCusto
merInfo()’/>


Now, each time we enter something into the zip code field, the JavaScript function getCustomerInfo() will run. That means it is time to roll up our sleeves and get busy with JavaScript. Before we dive into the getCustomerInfo() function, I have to create a function that will create the ‘request’ object. The request object is critical to making AJAX work. Without the request object we cannot send the query to the PHP script, and we cannot listen for the server’s response—this means we cannot update the page.

Writing the createRequest() Function
So I need to do the following:

1. Initiate a request object, setting it to ‘null’
2. Create a createRequest() function that will set that request object properly, depending on the browser I am using

The JavaScript is included in Listing 4. The createRequest() function first tries to set our null request placeholder with an XMLHttpRequest object. This particular object works with most non-Internet Explorer (IE) browsers—Mozilla, Netscape, Opera, Safari, and many others. If this process fails, then the function, in succession, tries to use one of two ActiveX Objects to make it work in IE. (Note that none of these approaches work in IE 5 for Mac. If you are using IE 5 for Mac, stop doing so. Use Safari or another modern browser.

If, by the end of the function, the request is null, an alert window will be displayed to the user. Now that we have created this all-important function, we can write our other function, getCustomerInfo().

Listing 4
<script language=”javascript” type=”text/javascript”>
var request = null;
function createRequest(){
try{
request = new XMLHttpRequest();
}catch (trymicrosoft){
try{
request = new ActiveXObject(“Msxml2.XMLHTTP”);
}catch (othermicrosoft){
try{
request = new ActiveXObject(“Microsoft.
XMLHTTP”);
}catch (failed){
request = null;
    }    }
  }
if (request == null){
alert(“Error creating request object!”);
  }
}


Writing the getCustomerInfo() Function
The getCustomerInfo() function is very simple. In it, we will take the zip code from the form, call the createRequest() function, send our information to lookup.php, and set other request object properties to receive a reply from the server.

In the first line of the function, we read in the value entered by the user into the form. Notice that we are using the DOM to get this information. Once you have captured the incoming zip code into a variable, we call the createRequest() function. Next, we build a URL variable by concatenating “lookup. php?zip=” and the zip code value we have already extracted with DOM. On the next line, we append a timestamp value to the end of the URL string, to trick IE into thinking we are asking for a different document; this way, IE will not cache our result set.

Listing 5
function getCustomerInfo(){
var zip = document.getElementById(“zip”).value;
createRequest();
var url = “lookup.php?zip=” + escape(zip);
//hack for IE caching
url = url + “&time=” + new Date().getTime();
request.open(“GET”,url,true);
request.onreadystatechange = updatePage;
request.send(null);


Finally, we come to the meat of the AJAX process. We use the open() method to request the URL (using GET) and setting asynchronous mode to ‘true’—in other words, we do not want to wait around for the server to respond. Setting this value to ‘true’ makes the whole thing an AJAX application because the user and the browser are both free to do whatever they want on the page—fill out other forms, run other processes, even run other JavaScript functions.

Because we are in asynchronous mode, we want to set a value for the request object’s onreadystatechange parameter. In this case, we are going to give it updatePage, which just happens to be the name of the JavaScript function that will update our page when we do get a response from the server. Be sure to always leave the parentheses from this value. You would get an error if you ran it as updatePage ().

The final step is using the send() method to send a null request. Why null? Well, you have already sent in the zip code as part of a GET request, so there is no need to send anything here. However, you have to run the request method or else nothing will work—so null it is! See Listing 6.

Listing 6
request.open(“GET”,url,true);
request.onreadystatechange = updatePage;
request.send(null);


Writing the updatePage() Function
The last piece of the puzzle is the updatePage() function, which will do the work of updating the HTML page. The code shown in Listing 7 is very brief and straightforward.

Listing 7
function updatePage(){
if (request.readyState == 4){
/* update the form with response from server!*/
var customerInfo = request.responseText;
document.getElementById(“resultset”).innerHTML =
customerInfo;
  }
}


The function tests for a readyState of 4 in the server’s response. Code 4 means that the server’s response has been loaded. For now, do not worry about the other states, which are 0 through 3. If the server’s response has been loaded, take the data (stored in the responseText parameter) and update the resultset DIV using the DOM.

That’s it! You are done. You have built your first successful (albeit simple) AJAX application using JavaScript, DOM, PHP, and XML. With less than 100 lines of front-end and back-end code, we have built a dynamic, useful page.

Summary
We have covered a lot of territory here, but with any luck you will have got the basics down for working with AJAX. Further, I have also tried to provide you with the basic building blocks you need to learn more about AJAX.


About the Author

Thomas Myer is the founder of Triple Dog Dare Media, an Austin, TX web consultancy that specializes in content management systems. He is the author of No Nonsense XML Web Development with PHP, recently published by Site Point. You can find out more about the book at http://www.tripledogs.com/ xmlbook. You can email him at tom@tripledogs.com.


   Related Links


Comment

Name:

Comment:

Captcha Verification !
captcha_image