Thursday, December 27, 2007

The absolute crux of AJAX. A short, short tutorial.

I've been unbelievably busy this past month so I haven't had much time to post any of the things I've been doing. I did, however, have to learn a little AJAX in order to complete a side project of mine. Since I found it a little difficult to find exactly what I needed easily on the web I wanted to share what I learned with anyone who might be Google-searching for how to write AJAX web pages.

First, a quick motivation for the problem. I want to give my user an entry form to tell me which country they are from. Once filled in, I want to populate a selection box for the region they are from, which of course depends on which country they select. After that I wanted them to chose the city. One really simple way to accomplish this is just to write out a list of all the countries, regions, and cities into a Javascript data structure. The problem is that there are more that 36,000 cities in the database I was using. Writing this all out to the user at once would make their browser time out.

What I really want to do is give the user just the countries to chose from first. Once they have chosen a country, I get the regions for just that country out of the database. Javascript doesn't have any database bindings and I don't want to have the user submit the page and have a new one come up for UI reasons.

What I want is for Javascript to go and ask the server itself. This is what AJAX is for. After reading a tutorial or two and picking out the pieces I needed, I found that this little snippet of code is all I need to do:

var req = new XMLHttpRequest();"GET", "getregions?countryid=" + countryid, true);
req.onreadystatechange = function () {
if (req.readyState == 4 /*complete*/) {
var data = eval('(' + req.responseText + ')');
... do something with data ...
req.send(/*no params*/null);

I simply create an XMLHttpRequest object. XMLHttpRequest is the Firefox version of the object. Different browsers require different objects, sadly. You can find out more about how to handle this problem here. Next I call the open method to connect to a script that I wrote to get a list of regions given a countryid. This program can be written in any language you want and acts just like any other CGI program. Instead of printing out HTML it prints out JSON. Most modern languages have a library for printing JSON or you can simply print it out using your own string building. You can learn more about what JSON looks like at

On the third line I set up an anonymous function to handle the network connection. It is called whenever the state is updated, waits until it's done, and then evaluates the JSON text into internal Javascript data. The function is then ultimately responsible for actually doing something with the data.

The readyState of the XMLHttpRequest object of course has more possible states than just 'complete'. If you'd like to learn how to deal with other states for make a progress bar or handling errors, then you can read more about the XMLHttpRequest object at w3schools.

The last line uses the send method to set the whole process in motion.

That's it. That's how AJAX and JSON work. Hopefully this tutorial will act as a decent spring board for anyone who wants to learn AJAX. There's a lot more out there of course and I've only really glazed over it. But if you need to get something up and running quickly this should do just fine.


Joe said...

don't think i ever thanked you for this. thanks!

Jack McKeown said...

Do you have the project posted anywhere so I could look at the source?