Are you handling Ajax Error ?

Yesterday I was working on an existing project developed by other company. One of my task was “Ensure that all ajax actions time out gracefully ” . In my programming career first time I see this type of task. Why? Because the other programmer who work for that company, don’t know or don’t care to write error handler code during ajax call.

But luckily they used jQuery for ajax related tasks, and that’s why its really easy for me to fix this. Normally using jQuery when I do ajax related tasks I use the following way jQuery.ajax()

jQuery.ajax({
           type: "POST",
            url: "ajaxurl.php",
           data: somedata,
           success: function(msg){
              //success task
           },
           error: function(xhr, statusText, errorThrown){
              //error handler to show a specific message
           }
         });

But that programmer used jQuery.post() to do ajax task

$.post("/ajaxurl.php", {
				data
			}, function(data){
				//success task
			}, "json");

So you’ll find there is no error handler. When I was updating his code, I thought to change his code by placing my way of jQuery ajax calling. Then I found some ajax code of him is too long like 100 lines of code. So it may possible I mistakenly change something important during ajax call. Then I read the jQuery.post() documentation and found

“Additional Notes:

  • If a request with jQuery.post() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method.”
So there is a global ajaxError() handler. That will rescue me to solve the problem of changing lots of code. So I implemented
$(function() {
    //global ajax error handler
    jQuery(this).ajaxError(function() {
       $("#loader").hide();
       alert('An ajax error occurred. Please try again!');
    });
});

And now if any ajax error occurs, this global method will call and hide the loader animation and alert the user.

So try to follow good practice whatever time it will take to write good code.

About mahmud ahsan

Founder And Lead Programmer at iThinkdiff.net

, ,

2 Responses to Are you handling Ajax Error ?

  1. Sarfraz November 5, 2010 at 10:59 am #

    That is useful piece of info. But I wonder what does the keyword “this” refer to in:

    jQuery(this).ajaxError(function() {….

    • mahmud ahsan November 5, 2010 at 1:40 pm #

      ‘this’ refers the jQuery Object or may be the html document object where it runs.

Leave a Reply