promotion

Wednesday, February 29, 2012

Handling global ajax errors using ajaxSetup

Jquery ajaxsetUp function is used for setting up default values for future ajax requests. Here i am going to use that method to handle all ajax errors.
function global_ajax_errors(){
  $.ajaxSetup({
    error:function(x,e){
      var errortext = "";
       switch(x.status){
         case 0:
           errortext ='You are offline! Please Check Your Network';
           break;
         case 404:
           errortext =  "Requested URL not found.";
           break;
         case 500:
           errortext = "Internal server error";
           break;
         default:
           if(e == "parsererror"){
             errortext = "Error. Parsing JSON request failed."
           }else if(e == "timeout"){
             errortext = "Request Time out";
           }else{
             errortext = "Unknown Error.".x.responseText;
           }
           break;
       }
       alert("Error:"+errortext);
    }
  });
}

Now, call this method at the time of loading the page. This will give alert message if any ajax error(internal server error, 404 page error, timeout etc) comes. You can handle other type of errors also by adding entry in switch.

No comments:

Post a Comment