Learning AJAX: Lesson 4 - Using The XMLHttpRequest To Get Your Data
Time to finish off my short series on simple AJAX. I started a while ago with an explanation on not using AJAX, then I backed that up with an unobtrusive way of adding a link to a page using JavaScript so that we only use AJAX when JavaScript is available. In the last post I explained, simply, the XMLHttpRequest and now I will show you what to do with it, culminating in the completion of a very simple, AJAX powered random quote generator.
Using The XMLHttpRequest
We start with the function I provided in
the last post, XHR() which returns an XMLHttpRequest
object. With the object we define the
URL of the file we
want to return, what we do while waiting for the response and what
to do when we receive the response. It looks a bit like this:
var request = XHR();
request.open('get',URL);
// get the file you want
request.onreadystatechange=function() {
if (request.readyState == 1) {
// what to do while waiting
}
if(request.readyState == 4) {
if (request.status && /200|304/.test(request.status)) {
// what to do when you get the response
}
else {
// what to do when the response is an error
}
}
request.send(null);
The first part is simple, we get our XMLHttpRequest and we
immediately set up where we intend to get our file from, by calling
request.open. I have called 'get' as the
http in this
example, but you could also use 'post'. The URL is the one that you
wish to return.
Next we set up what to do whilst we wait for the file to arrive and
what do when it does. There are 5 states we can attach event
handlers to and they correspond to the following
readyState of our request.
- 0:
- No connection
- 1:
- Connection loading
- 2:
- Data loaded
- 3:
- Connection is interactive
- 4:
- Connection complete
I have only used 2 of these states for my example, 1 and 4, content
loading and everything complete. While the content is loading, it is
quite common to display a message or animated gif to indicate that
the data is loading. When the connection is complete, any of the
normal http codes could be returned to distinguish the result, so my
example checks for this too using the test method of
request.status. If the status is 200
(OK) or 304 (not modified) then we have the file safely and can
carry on, any other results and we should display an error message.
Once these event handlers have been identified, we need to send the
request, in our case we send no parameters, so choose
request.send(null).
Actually, there is one little problem. Safari's cache tends to cache
response statuses and doesn't trigger any changes if we write the
function as above. To combat this we need one extra line:
request.setRequestHeader( 'If-Modified-Since', 'Thu, 31 Oct 2007
00:00:00 GMT' );
will tell the browser that the data has changed since the date you
add. I have put in a date from a couple of days ago, but any time in
the past will work.
Ready To Use AJAX
Originally I started with the intention of writing a random quote generator that could update using AJAX. You can see the fully working random quote generator example and the source to see what I did. Most of the code is commented as in the series of posts and any that isn't deals with the manipulation of my small quotes.txt file to print out the new quote. This script is intended as an example, but you are free to borrow it and use it, just let me know if you need any help adapting it.
I hope you have enjoyed this simple look into AJAX, I hope to bring you more complex examples in the near future. If there ever is anything you want to read on this blog, whether it be more JavaScript, HTML, CSS, web standards or anything, please let me know.