What is ajax?
Along with web 2.0, “ajax” has been a popular buzzword lately. Before getting into it, I always though this was a name for some complex libraries doing all kinds of black magic.
But what Ajax really is, it’s just a simple HTTP request trough javascript. Think of it as loading a web page. You need to type in the url and you shall receive any text (e.g. plain HTML) that is under that url. What to do with that text is based on your parser / browser. You can do the same with javascript. Here is how you do it:
- Create an object to hold your request
var ajax = new XMLHttpRequest(); - Prepare a connection to the server, say google.com
ajax.open("GET", "http://www.google.com", true); - Tell the script what to do when it gets a response
ajax.onreadystatechange = function () { /* do something */ }; - Send the request
ajax.send(null);
This is basically it. You have requested a website, and have gotten some text back. An everyday task really. Of course, you could set some HTTP request headers, for instance the user agent, or cache control:
ajax.setRequestHeader('User-Agent', 'My javascript');
ajax.setRequestHeader('Pragma', 'no-cache');
(but make sure you set these before sending the request)
Now, what do I do in the response function, I hear you ask. ajax.onreadystatechange function, which you set, gets called every time something happens to our request. So it gets called multiple times for one request. To put it simply, when ajax.readyState == 4, your request has finished processing and the server’s response text is inside ajax.responseText. This is a string (bunch of text) and you can do anything you like with it.
A word of caution though - Internet Explorer does not use “new XMLHttpRequest()” to generate a request, but uses “new ActiveXObject("Microsoft.XMLHTTP");” instead.
There really isn’t much more to it. You just have to incorporate it into your application. For some further reading, try these links:
- The XMLHttpRequest Object at w3schools
- A basic ajax request function at quirksmode
- “Getting Starter with AJAX” by BrainJar.com
And here are some questions you might want to ask yourself when developing your first ajax application:
- What happens in browsers without ajax or even javascript support?
- What if the server you aretrying to acces is down? What if it returns an unexpected result?
- What happens when multiple requests are sent at once?
And of course, there are some usability concerns with ajax - it breaks browser’s native controls (back, forward, reload, …), can confuse the user if he doesn’t know what is happening after clicking a link, etc.
As with every other technology, ajax can be very powerful and handy when in the right hands, but can also ruin a website when abused. But it’s very easy to begin with - don’t get fooled by the fancy name, it’s just 4 lines of javascript.










