How do I catch an Ajax query post error? How do I catch an Ajax query post error? ajax ajax

How do I catch an Ajax query post error?


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");  }});


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.


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