Capturing Http Status Code/Response for AJAX Error Handling
One dilemma I encounter when making AJAX based modules is when a fragment of JavaScript code makes a request and it seems like it is taking forever (the gif images progress bar is still there doing its job) and not displaying a response at all. Second dilemma is the response is written on the container element on the page and it screw up all the rest of the page because of some internal server error generated by the processing file.
Back when I was doing VB6 gracefully handling errors is one of the things that we do. But yes there were times when I get bored and put on funny labels on the error handling routines.
On Error Goto Hell
Call WashTheDishes()
Call ScratchMyBack()
Call GetMeSomeMoney()
Hell:
Msgbox “Can’t do that Boss!”
Well I can crack up some jokes in the code sometimes. :p
When I shifted to Web Development 6 years ago, error handling is still there but a bit different (VBscript). In PHP you can suppress these warning messages at will using the “@” symbol on every built in PHP function. Or you can use the Error Object and extract some additional information on the occurring errors. In PHP 5 Try catch construct is introduced for error handling same also for C#. I’m sure there are a lot of other error handling classes in both language that is not covered here but my point is, it is the inevitable.
Interestingly enough JavaScript has its own error handling too. In fact I use the Try catch construct to capture javascript errors on page and write back to the user some friendly messages instead. Unfortunately AJAX is a little different since it is requesting contents on other files or other server files and process the response and output them all in the container element. So how do I know that the AJAX request I made went wrong and the processing file generates a lot of crappy messages, should we display that to our non technical user? I say no! There must be other ways to get passed these dilemmas and one of them that I think is helpful is the Status Code and the Status Description of the Response.
How do I do that?
Whether you are using IE6’s (and earlier version) activeX object Microsoft.XMLHTTP as transport or the native XMLHttpRequest object on Mozilla ,Netscape and Safari and IE 7 you should be able to access the property “status” and “statusText” to retrieve the status information.
The fragment of code below is saved as process.php
<?php
if($_GET['action']){
//Manipulate/Send Status Code here. Refer to W3C http 1.1 codes
header("HTTP/1.1 500");
die();
}
?>
<script>
function sendRequest(){
var client = new XMLHttpRequest();
client.onreadystatechange = function(){
if (this.readyState == 4)
//check request status
switch (client.status) {
case 200:
alert("Success")
break;
case 500:
alert("Internal Server Error");
break;
default:
alert(client.status);
break;
}
}
client.open("GET", 'process.php?action=send', true);
client.send(null);
}
</script>
<input type=button onclick="sendRequest()" value="Send"/>
The whole idea is, if you encounter an error in the processing file, modify the header and send 500 (”Internal Server Error”) to header status code. But if all is well as you have expected 200 “OK” is automatically sent to the browser.
<?php
//using try catch in php 5.xx
try{
goToTheMoon();
}catch(Exception $e){
//Exception is generated by PHP because of some error
//Modify header status to 500
header("HTTP/1.1 500");
die();
}
?>
In ASP.NET you can access Response Object to manipulate the header status code
<%
try{
goToTheMoon();
}catch(Exception){
//catch without assigning to variable
//Modify header status to 500
//Instead of using Response.Status="500 Internal Server Error";
//Use below instead
Response.StatusCode=500;
Response.StatusDescription="Internal Server Error";
}
%>
One thing to note is the network errors when requesting documents. I’ve done some few testings on FF3 and IE7. FF3 returns 0 while IE7 returns 12xxx series of network error related codes. If client.status return a number greater than 12000 i guess its safe to assume that this is IE and it is telling us that the browser cannot reach the resource destination. Same is true for Firefox returning code less than 1 (zero). If we are using JavaScript frameworks all of these is already wrapped into a single object for ease of usage. Sometimes it’s good to see how stuff works without us being abstracted away by these JavaScript frameworks to learn. One we have learned a handful, i think it’s a good thing to make use of JavaScript frameworks for agile web development.
If you think there is a better approach you can post a comment
Posted in General Javascript Programming, How to Section
![[del.icio.us]](http://genusproject.com/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://genusproject.com/wp-content/plugins/bookmarkify/digg.png)
![[Google]](http://genusproject.com/wp-content/plugins/bookmarkify/google.png)
![[StumbleUpon]](http://genusproject.com/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Windows Live]](http://genusproject.com/wp-content/plugins/bookmarkify/windowslive.png)
![[Yahoo!]](http://genusproject.com/wp-content/plugins/bookmarkify/yahoo.png)
![[Email]](http://genusproject.com/wp-content/plugins/bookmarkify/email.png)

July 8th, 2008 at 6:02 am
Fantastic recommendation and avid instructions. Thank you very much! Is this information applicable to the new version of Firefox (3)?
July 9th, 2008 at 7:56 am
Yes, this is tested on Firefox 3 and thanks for dropping by
July 9th, 2008 at 3:17 pm
nice naman eto kuya (^_^) nga pala… pwede ko po malaman kamusta na dito parang tumataas na ata PR natin ha (^_^) Nice!
July 9th, 2008 at 4:40 pm
Di naman po. Ok lng naman po d2. tina try ko lng dina na every month at least meron akong 2 articles na mai share :p
July 26th, 2008 at 8:44 am
Added. Nice work on this one. Btw, my blog is dofollow, stop by and grab a link. Bompa
July 27th, 2008 at 7:52 pm
Nice post, you got some good points there - thank you.
July 30th, 2008 at 1:44 pm
awesome article sensei…
i just started working with ExtJS 2 weeks ago and I’m getting better at it, hope this site of yours can give me some tips on AJAX/JavaScript as I think it would.
July 30th, 2008 at 7:06 pm
I will try my best to share some of the stuff i know
August 29th, 2008 at 6:59 pm
Hi
Nice Article..
I am using ajax in my code.. aftr updating to FF3 it stopped working. In my ajax response text i am having some symbols like +,^.| etc. i am getting not well formed as error in error console.. please help me solve this.
August 30th, 2008 at 9:09 am
Can you post the responseText here? you can view that using firebug console under response tab.