Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.post() failure callback function?

Let's say I've a code:

$.post("test.php", function(data) {
   alert("Data Loaded: " + data);
});

Is there any way to check if the request have failed (e.g. due to the timeout)?

like image 752
McRonald Avatar asked May 18 '11 15:05

McRonald


2 Answers

Yes there is, from the jQuery documentation:

$.post("test.php", function(data) {    alert("Data Loaded: " + data); }) .fail(function() {     alert("error");  }) 

Update: drake7077: "error is deprecated as of jquery 1.8, use .fail()"

like image 120
amosrivera Avatar answered Sep 18 '22 21:09

amosrivera


Two possibilities:

  1. You can register an "ajax error" general callback, which will be called when any ajax operation fails:

    $(document).ajaxError(function(event, jqXHR, settings, exception) { ... });
    
  2. You can fall back to $.ajax() instead and include your own error handler directly.

edit — @amosrivera is right - the new "Deferred" return values allow for introduction of handlers. Those are available with jQuery 1.5 and newer.

like image 39
Pointy Avatar answered Sep 18 '22 21:09

Pointy