AJAX: A Primer
First off, what is AJAX? AJAX stands for Asynchronous JavaScript And XML. What does that mean? Basically, it means that you can call up other scripts and retrieve dynamically generated content (or perform simple actions) without ever leaving the current page. It’s how a large number of sites let you log in nowadays, and on what Yahoo! Mail Beta is based. It became popular through Google Suggest, where AJAX is the framework behind that little list that pops up below the search bar while you type in your query.

In Google Suggest, AJAX calls up an external script while you type, looking through a list of popular search queries, and return those that start with the text you are typing, providing suggestions for your search. It is quite useful in that it allows the visitor to see a search query that might return more (or better) results than the one the visitor had in mind.
AJAX isn’t a programming language in itself; it is simply a method of combining JavaScript and the dynamic programming language of your choice (ASP, PHP, etc.) to run another page’s server-side script. There are two parts to an AJAX script: the originating page, where the user is located; and the external page, containing the script that AJAX calls.
We’re going to create our own little page with a “name” text field. When somebody types text into that field, the page will call up an external script that returns the current time. (Sure, we can use plain JS to do this, but this is just a demonstration!)
To start off, we will create the HTML page with the form.
<html>
<head>
<title>AJAX Test Page</title>
</head>
<body>
<form name="testform">
Name: <input type="text" name="inputname" /><br />
Time: <input type="text" name="currtime" />
</form>
</body>
</html>
Pretty basic, right? So far we have the text “Name”, followed by a text field in which the user can enter text. Nothing else happens at the moment, as you can see.
We need to call up our script when the user types in text. The best handler to use for this is the onkeyup event handler. Add the event handler and have it call up a function we will then create:
<input type="text" name="inputname" onkeyup="getTime()" />
Different browsers use different methods to create the XML-HTTP Request object we will need. Internet Explorer uses an ActiveX object, while most other browsers use a built-in JavaScript object. We will use try and catch statements to generate the correct object.
Let’s define the function that will return the XMLHttpRequest object. In the <head> section, add some JavaScript:
<script language="javascript" type="text/javascript">
function getXHObject() {
var xmlHttp = null;
try {
// For Firefox, Opera 8.0+, and Safari:
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer (below 7.0, and 7.0+):
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
The above script will attempt to create the built-in JS object, which will work for most non-IE browsers. If that doesn’t work, then it tries to call up one of the IE-supported methods. The first one works with versions of IE from 5.5 to under 7.0. The second one works with IE 7.0+. Finally, it returns the XML-HTTP object.
What if none of them work? In that case, the user’s browser is incredibly obsolete and does not support AJAX at all. Sure, this isn’t 100% compatible with all browsers, but so few people use ancient web browsers that it doesn’t matter much anyway. It comes to the point where they really should upgrade anyway, to be totally honest.
Next, we will create the getTime() function, which will call up the external script and retrieve the needed information.
var xmlHttp; // This var must be global
function getTime() {
// If the input mattered, we would check for blank or invalid input here
// Create XML-HTTP object
xmlHttp = getXHObject();
// Check if null - browser is obselete
if (xmlHttp == null) {
alert('Your browser does not support AJAX!');
return;
}
// The URL we will call - if input mattered, we would add a query string of some sort.
var url = 'gettime.php';
// Required AJAX code
xmlHttp.onreadystatechange = stateChanged; // Specify function that will output info.
xmlHttp.open('GET', url, true); // Open the URL for sending...
xmlHttp.send(null); // ...and send the request.
}
If the input affected the output (such as getting information based on user input), then the above getTime() function would have included the input as a parameter, and we would have checked the input to make sure it was valid. We would also have generated a URL with the input in the query string, such as getusername.php?id=123.
Next, we will define the stateChanged() function, which is called while the XML-HTTP request is working.
function stateChanged() {
if (xmlHttp.readyState == 4) {
// Output was received
document.testform.currtime.value = xmlHttp.responseText;
} else {
// Nothing was received yet, but the XML-HTTP request is working.
// We may want to generate a message that asks the user to wait.
}
}
The above function will set the currtime text field’s value to the response text — the output received from the gettime.php external script.
Finally, we will set up the gettime.php page itself. Whatever we echo out will be the response text when called via AJAX. In a new file, we will use PHP to get the current time.
<?php
echo date('g:i:s A');
// Return something like "1:45:23 AM"
?>
And that’s it!
Basically, here’s how it works: The user types in a value into the “Name” field. After each keystroke, the getTime() function is called and creates an XML-HTTP object. This is then used to communicate silently with gettime.php, which outputs the time. This output triggers a Ready State of 4. The stateChanged() function is then used to take the output and put it into the “Time” text field.
Now you know how to utilize AJAX, and have just increased your web development arsenal. As stated above, you can have output that changes depending on the user input. For example, you could have a text field that receives a User ID as input, and the external script will take that ID, query a database, and return that user’s full name, or some other piece of information.
Furthermore, instead of using onkeyup as the event handler, you could have a button click (onclick) or a click away from the text field (onblur) act as the trigger.
On a side note, I promise that future posts will not be as long as this one. I just wanted to get an AJAX primer out of the way, kind of as our starting big bang.
Happy coding!
No comments yet.