1. Home
  2. Computing & Technology
  3. JavaScript

Introduction to Ajax

3. Response Event Handler

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

XMLHttpRequest Open Request

As we are making an asynchronous request to the server we are not going to wait around for the server to send back its reply (as we would with a synchronous request). We therefore need a way to detect when the server has returned the requested information.

Fortunately our XMLHttpRequest object has a property called readyState that contains one of several values depending on the current status of the request. An associated event handler called onreadystatechange allows us to attach processing that will be run whenever the current status in the readyState field is changed.

ajaxObj.onreadystatechange = function() {
ajaxObj.processRequest();}

Again we add this new code to the end of the code that we have already created.

We next need to create our new method (which we have called processRequest) to actually perform the processing that we want when the readyState changes. The readyState field actually has five possible values although not all values are actually set by all browsers. These values are:

  • 0 (uninitialized) - we have created our AJAX object but haven't opened it yet.
  • 1 (loading) - we have called open but haven't yet sent the request.
    This is the status that we would have if we run the code we have so far.
  • 2 (loaded) - we have sent the request.
  • 3 (interactive) - a partial response has been received.
  • 4 (complete) - a complete response has been received and the connection has been closed.

The only one of these values that we are actually interested in is the last one since this is the one that tells us that we have received the complete response. We can therefore add the following code to initially handle the response:

ajaxObj.processRequest = function() {
if (this.readyState == 4) {
// got response
}
}

We'll keep this piece of code separate from the rest of what we have written for the moment and return to it later.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.