By Mitchell Harper
AJAX -- or Asynchronous JavaScript and XML is the newest buzz word in web development. Utilizing a client-side XMLHTTPRequest object, HTML, JavaScript and CSS, you can replace the page refresh that has (up until a few months ago) been a mandatory part of posting data back to a web server.
In this article I'm going to show you 3 simple and practical uses for AJAX on your web site. You'll need to know a bit of HTML, JavaScript and PHP to follow along, but I'll do my best to explain everything in simple terms so you don't get lost!
Note: In this article I will assume that you're running a PHP web server.
Enabling Client-to-Server Communication
There are 2 simple functions that are required for AJAX to work. They handle everything needed to pass data to the server and also to process the response back from the server. We will create a .JS file containing these 2 functions. They will be used in each of our 3 AJAX examples.
Create a new file in your favorite text editor and call it ajax.js -- copy and paste the following code into the file and save it:
function DoCallback(data)
{
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open('POST', url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(data);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject('Microsoft.XMLHTTP')
if (req) {
req.onreadystatechange = processReqChange;
req.open('POST', url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(data);
}
}
}
function processReqChange() {
// only if req shows 'loaded'
if (req.readyState == 4) {
// only if 'OK'
if (req.status == 200) {
eval(what);
} else {
alert('There was a problem retrieving the XML data: ' +
req.responseText);
}
}
}
Now that you've created your ajax.js file, let's move onto our first use for AJAX on your web site.