views:

130

answers:

3

I would like to catch the error and show the appropriate message if the ajax request fails. My code is like the following, but I could not manage to catch the failure ajax request.

function getAjaxData(id)    
{
     $.post("status.ajax.php", {deviceId : id}, function(data){

        var tab1;

        if (data.length>0) {               
            tab1 = data;
        } 
        else {
            tab1 = "Error in Ajax";
        }       

        return tab1;
    });
}

I found out that, "Error in Ajax" is never executed when the Ajax request failed. How to handle the ajax error and show the appropriate message if it fails? Thanks very much.

+2  A: 

you can use .ajax

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  },
  error(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");
  }
});
choise
A: 
$.ajax({
  type: 'POST',
  url: 'status.ajax.php',
  data: {
     deviceId: id
  },
  success: function(data){
     // your code from above
  },
  error: function(xhr, textStatus, error){
      console.log(xhr.statusText);
      console.log(textStatus);
      console.log(error);
  }
});
jAndy
+1  A: 

A simple way is to implement ajaxError:

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.

e.g.:

$('.log').ajaxError(function() {
  $(this).text('Triggered ajaxError handler.');
});

I would suggest reading the ajaxError documentation, it does more than the simple use-case demonstrated above - mainly it's callback accepts a number of parameters:

$('.log').ajaxError(function(e, xhr, settings, exception) {
  if (settings.url == 'ajax/missing.html') {
    $(this).text('Triggered ajaxError handler.');
  }
});
karim79
+1 - I would add that this handler gets several arguments, so you can display the actual error, response code, url, etc.
Nick Craver
@Nick - added that in.
karim79
@karim - Excellent...but you can't get a +2 out of me! :)
Nick Craver