How do I catch an Ajax query post error?

JqueryAjaxPostError Handling

Jquery Problem Overview


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 failing 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 do I handle the Ajax error and show the appropriate message if it fails?

Jquery Solutions


Solution 1 - Jquery

Since jQuery 1.5 you can use the deferred objects mechanism:

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling
    });

Another way is using .ajax:

$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
        alert( "Data Saved: " + msg );
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
     alert("some error");
  }
});

Solution 2 - Jquery

jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.

Example:

$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    });

Prior to jQuery 1.8, the function done was called success and fail was called error.

Solution 3 - Jquery

$.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);
  }
});

Solution 4 - Jquery

$.post('someUri', { }, 
  function(data){ doSomeStuff })
 .fail(function(error) { alert(error.responseJSON) });

Solution 5 - Jquery

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.

For example:

$('.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 its callback accepts a number of parameters:

$('.log').ajaxError(function(e, xhr, settings, exception) {
  if (settings.url == 'ajax/missing.html') {
    $(this).text('Triggered ajaxError handler.');
  }
});

Solution 6 - Jquery

You have to log the responseText:

$.ajax({
    type: 'POST',
    url: 'status.ajax.php',
    data: {
    deviceId: id
  }
})
.done(
 function (data) {
  //your code
 }
)
.fail(function (data) {
      console.log( "Ajax failed: " + data['responseText'] );
})

Solution 7 - Jquery

you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform...

quickie example:

ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
    alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );

Solution 8 - Jquery

In case you want to utilize .then() which has a subtle difference in comparison with .done() :

return $.post(url, payload)
.then(
	function (result, textStatus, jqXHR) {
		return result;
	},
	function (jqXHR, textStatus, errorThrown) {
		return console.error(errorThrown);
	});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTTCGView Question on Stackoverflow
Solution 1 - JquerychoiseView Answer on Stackoverflow
Solution 2 - JqueryMichael VenableView Answer on Stackoverflow
Solution 3 - JqueryjAndyView Answer on Stackoverflow
Solution 4 - JquerymarkneryView Answer on Stackoverflow
Solution 5 - Jquerykarim79View Answer on Stackoverflow
Solution 6 - JquerymanoloView Answer on Stackoverflow
Solution 7 - JqueryMark GiblinView Answer on Stackoverflow
Solution 8 - JquerypanagiotisView Answer on Stackoverflow