This is a simple tutorial that will help you get down and dirty with some simple AJAX. You might be wondering why I’m writing an AJAX tutorial on my Web site. That’s probably because the Jays suck, everything to say about C-61 has been said, and I’ve got nothing about music other than that Opeth’s new album Watershed is superb. Get it, you won’t regret it. Finally, I found a lot of blogs while searching Google for tutorials, and I’m hoping I can snag some people and force them read my crap, too.
Anyway, I will assume that you know what JavaScript is and how to write it. I’ll also assume that you have an idea of what AJAX is. At least know that, for our purposes, it’s not a city near Toronto or a cleaning product. To recap, AJAX (or Advanced Javascript And Xml) refers to the technique of running HTTP requests in JavaScript to update elements on a Web page dynamically, without reloading it. This can provide a much better user experience, especially for Web applications. Note that I’m just introducing you to some basic code that you’ll need to get started. Where you go from there is up to you.
If you’re just looking for some code to grab, I won’t keep you waiting…
if (window.XMLHttpRequest) {
requestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
requestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
requestObject.open("GET", "./YourPage.html");
requestObject.onreadystatechange = function() {
if ((requestObject.readyState == 4) && (requestObject.status == 200)) {
returnedText = requestObject.responseText;
// todo: whatever you want with the response data
}
}
requestObject.send(null);
Confused? Don’t worry, it’s very simple. Let’s look at it piece by piece.
JavaScript handles HTTP requests with an object. In Firefox, Opera, Safari, Konqueror, and basically every browser that isn’t Microsoft Internet Explorer, the object is called XMLHttpRequest. In Internet Explorer, it’s an ActiveX object called Microsoft.XMLHTTP. Both objects function in basically the same manner.
The first thing you need to do, then, is check which one is available. That’s exactly what this code does:
if (window.XMLHttpRequest) {
requestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
requestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
Here, we’re saying that if window.XMLHttpRequest exists, then create a new object called requestObject and make it an XMLHttpRequest object. Otherwise, if window.ActiveXObject exists, then create a new object called requestObject and make it an ActiveX XMLHTTP object. Whether we’re on IE or uh… not IE, we get an object called requestObject.
Next, we specify what file we want to request, and the method of request. The method of request is the command sent to the HTTP server, and is either GET or POST. Most of the time, we’ll be using GET, so we’ll use it for simplicity. If you want more information on the difference between GET and POST, check out this page.
To specify the file and method, use the .open method. The URL to the page is relative to the current page. You can also make a call to another Web server by using http:// followed by the domain, but be aware that most web browsers will find this suspicious and block it.
requestObject.open("GET", "./YourPage.html");
The next block of code handles what’s going to happen when the Web server responds. The event that is triggered when this happens is onreadystatechange. By declaring a function here, we can do as many things we want with the data. Note the two conditions that must be met. The property readyState is equal to 4 (or ‘complete’) if the object has been properly initialized and loaded. The status 200 is Web server speak for success. You’ve probably encountered other Web server codes like 404 when a file is not found or 500 when a script malfunctions or the server crashes.
requestObject.onreadystatechange = function() {
if ((requestObject.readyState == 4) && (requestObject.status == 200)) {
returnedText = requestObject.responseText;
// todo: whatever you want with the response data
}
}
In the above code, we’ve assigned the value returned by the server to returnedText. This means you can do anything with it that you could do to a string. You could assign it to a form field or div using the document object model (DOM). You could parse it and perform some action based on its contents. You are limited only by your imagination. A common use of this is to execute a script which grabs some data from a database and sticks it in a div or a field.
Anything that you want to with the data must appear in the function triggered by onreadystatechange. Recall that AJAX stands for Asynchronous Javascript And Xml. Once the query executes, the script will NOT wait for a response from the server! It will keep on executing! The only instructions that will be held until the server responds are those in the onreadystatechange function. Commit this to permanent memory and never forget it, or your applications will behave erratically. You are of course welcome to call other functions from this function if you want to organise and modularise your code.
The final step is actually kicking off the request. And that’s all!
requestObject.send(null);
Before you jump around the room shouting “ZOMG I NOE TEH AJACKS LOL ADD IT TO THE RESUME!” there are a few problems with the code I’ve given you. The example code is fully functional, but if you’re actually building an application, there are a few things you will not want to overlook.
Error handling
I know, I hate error handling too. But there’s a reason we have to spend so much time handling errors: users are garbage who will do things to your application that you thought were not even possible. When they inadvertently screw it up so bad they crash your program or find weird bugs, I call that haccidents. Remember, though, that the reason you’re adding AJAX to something is probably to make it more user friendly.
You might find that you deal with old browsers often which do not have support for AJAX. If this is the case, you would want to add an else clause to the first if statement that attempts to create an object, and perform some alternate actions. You might also want to display a custom error message if the HTTP request status comes back 404 or 500.
Unresponsive server
If your server goes down, your requests are probably not going to come back. This might happen if a user has your application open for a long time, or perhaps even has problems with their Internet connection. Instead of getting a blank page or an error when submitting a form, your application just won’t respond. To make sure they won’t blame you, you should probably handle this scenario and allow the application to fail gracefully. This is especially true if your application deals with serious data like banking or medical records. If this is what you’re working on, and you’re learning how to code from my blog, I’m kind of scared. Just sayin’.
