1. Home
  2. Computing & Technology
  3. JavaScript

Introduction to Ajax

6. Success or Failure

clr gif

We already have our method set up ready to handle the information passed back from our AJAX request and have the if statement in place that confirms that the request is complete. Of course just because a request is complete doesn't mean that it worked and returned the needed information. Perhaps the server was down or there is a typo in the name of the server side script, or we don't have authority to access that script. Just because the request is complete doesn't mean that it worked. What we need to do now is to determine whether the request succeeded or failed.

We can determine the status of the completer request by testing the status property of our request. This field contains the same codes as are returned when a web page is accessed (I am sure you have come across 404 not found errors before now). The code for a successful return is 200 so we need to add a test for that into our code before trying to process what we got back.

ajaxObj.processRequest = function() {
if (this.readyState == 4) {
if (this.status != 200) {
alert('Error : Status '+this.status+' returned.');
} else {

// got response
}
}
}

In some (but not all) browsers there is also a property called statusText that contains a description of what the error is. Because this is not defined in some browsers, I recommend that you avoid using this field and build your own error messages based on the status property.

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.