I have been trying out AJAX tools such as the YUI to make web applications more responsive. Reminding myself that AJAX stands for Asynchronous JavaScript and XML, I thought I’d try to understand better then asynchronous side of it.
The xmlHttpReq object is responsible for the responsiveness of an AJAX application. It allows the JavaScript to make asynchronous HTTP request (POST or GET) to a script. The same xmlHttpReq object handles the output of the script through a callback function.
The example that I wrote is an Australian postcode lookup. Basically, the user enters a postcode which is then posted by the xmlHttpReq object to a PHP script. The script returns comma delimited details of the postcode, which is processed by the callback function, and displayed nicely to the user.
Click here to see working example.
The Query String
We post the data to the script using a query string; the string will later be passed into the xmlHttpReq object.
In our case the data we post to the script is the postcode; for example ‘PostCode=3000′.
var postcode = document.forms[0].PostCode.value; // generate the query string to post to the script var queryStr = ‘PostCode=’ + escape(postcode);
It is possible to pass more variables with the query string; for example ‘PostCode=3000&Location=Melbourne’.
Note that we encode the postcode when building the query string using the escape function.
The xmlHttpReq Object
Now it is time to create the xmlHttpReq object. We initialise it differently for Internet Explorer and Mozilla, thus we need to detect the user’s browser.
var xmlHttpReq;
// Determining which browser we are dealing with
if (window.XMLHttpRequest)
{
// this is required if the browser is Mozilla
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.overrideMimeType(’text/plain’);
}
else if (window.ActiveXObject)
{
// this is required if the browser is IE
xmlHttpReq = new ActiveXObject(”Microsoft.XMLHTTP”);
}
We can now set the parameters for the xmlHttpReq object. The open function takes three parameters: HTTP request method, script to send the request to, and a flag that determines whether the request is asynchronous.
var strURL = ‘postcode_lookup.php’; xmlHttpReq.open(’POST’, strURL, true);
Finally we set the callback function displayPostcodethat will handle the script’s output.
xmlHttpReq.setRequestHeader(’Content-Type’, ‘application/x-www-form-urlencoded’); xmlHttpReq.onreadystatechange = displayPostcode;
The Callback Function
The callback function that we set in the previous section will be called whenever the state of the request has changed. When the request is completed, the xmlHttpReq.readyState will be set to 4.
function displayPostcode()
{
document.getElementById('outputDiv').innerHTML = "";
var postcodeData = "";
var output = "";
if (xmlHttpReq.readyState == 4)
{
postcodeData = xmlHttpReq.responseText.split(",");
output = "";
// processing information produced by the script
if( postcodeData.length > 1 )
{
output = "Postcode: " + postcodeData[0] + "<br/>";
output += "Locality: " + postcodeData[1] + "</br>";
output += "State: " + postcodeData[2] + "<br/>";
output += "Category: " + postcodeData[9] + "<br/>";
}
else
output = "Postcode not found!";
// writing output into div
document.getElementById('outputDiv').innerHTML = "” + output + ““;
}
else
{
document.getElementById('outputDiv').innerHTML = "loader.gif";
}
}
The callback function simply updates a div by looking at the information returned by the xmlHttpReq.responseText. While the request is not finished, we display a loading animated gif.
The Request
We have a xmlHttpReq object setup, and a callback function to handle the data returned by the script. Now we are ready to send the HTTP request to the script.
// post to script xmlHttpReq.send(queryStr);
That’s it! We have a simple AJAX Postcode search. For this example the script is set to sleep for a couple of seconds, just so we can show off the loading gif :)
The zip file with the source code can be downloaded here.
The loading gif was originally downloaded from here, and the data with the postcode information was downloaded from the Australian Post website.
WOW…nice man…
I also like Aikido, and roller bladding :D (well, until I ran into a parked car) ;( lol…
Nice script man…
Thanks Eddie!
Yes, cars and roller blades don’t go together very well. :)
Whereabouts do you train Aikido?
Yeah, I was getting towed behind my friends car, he missed a gear turning teh corner, I still held on (which was stupid) and gained too much spoeed, only place to go was into a parked car, because there was a heavy traffic corss street, with loads of cars, and I was surely dead if I went there. So I chose the back of a CRV instead :(..Broke my legs and smashed my face. but yeah, silly me :(
Hey, yeah, I dont do Aikido, I just luv the art :D..I also luv Ninjitsu. My friend use to teach Hapkido at his home too, that was pretty fun :D
Hey, I figured out how to change the zones in the CSV file too :D…I never knew that’s how people kept databases.
Could I ask if you have the CSV file for this script?
Thanks Marcel
Sounds like a painful experience! Lucky you did not hit any moving cars.
Glad you figured out how to tweak the script. You can get the CSV from http://members.iinet.net.au/~matjandr/apps/postcodesearch/pc-full_20071128.csv
That is a modified version from the one I picked up from the Australia Post website.
Databases are different from CSV files. A database is basically a collection of data/information that is managed by a software; while a csv file is simply a text file with records delimited by commas. Both of them can be used to store information, so it just depends on the complexity of your solution.
A CSV file was enough for me since my example was very simple; a database would be overkill. And also because my web hosting does not give me access to a database. :)
Cheers!