Wednesday, June 23, 2010

Error Checking with HTTP Status Codes in Ajax

Error checking is very important when working with AJAX. If you are inserting data directly into a page, you must ensure at the least that the request completed succesfully. While the request may have been completed (determined by a ready state of 4 - see above), it may not have been succesful - for example, if the page was not found, or if access was denied. We can handle this using HTTP status codes.
You will be familiar with the most commonly seen status code - 404, or file not found. The most commonly used code, however, is 200 - OK. We can check the HTTP status code returned by the web server using the status property of the XMLHttpRequest object. So, our previous example should check that the ready state is 4 and the status code is 200:
xhrobj.onreadystatechange = function()
{
  if (xhrobj.readyState == 4 && xhrobj.status == 200)
  {
    if (xhrobj.responseText)
    {
     document.write(xhrobj.responseText);
    }
  }
};

Common status codes

Here is a list of common status codes:
200 OK
400 Bad Request
403 Forbidden
404 Not Found
50x Server Errors
500 Internal Server Error

No comments:

Post a Comment

 

Followers