3

I have a question about ajax success. So in previous situations I have returned Data something like ID but now in this case I'm returning entire table. So I would like to check if Ajax was successful(200 OK) before I retrieve my data. What is the best way to do that? Also I use new way to retrieve data and check for errors with JQuery. Here is example of my code:

<div id="box"></div>

function getSlots(fld){
    var userID = '134';

    $j.ajax({
        type:  'POST',
        url:  'AjaxData.html',
        cache:  false,
        data:  {'userID':userID},
            dataType: "html",
            async:   false
        })  
        .done(function(html){
            $j('#box').html(html);
        })
        .fail(function(jqXHR, textStatus, errorThrown){ 
            gwLogIt(errorThrown);
        }); 
    }
espresso_coffee
  • 5,980
  • 11
  • 83
  • 193

2 Answers2

4

You don't need to check. The various callbacks are called under the following conditions:

  • .done() or success: are called when the AJAX call is successful.
  • .fail() or error: are called when there's an error (either from the server or in the jQuery code that parses the response).
  • .always() or complete: are called in either case.
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

from official docs:

$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});

http://api.jquery.com/jQuery.ajax/

also if you use something like babel to transpile ES6, you can use fetch api for ajax calls. I personally stopped using jQuery ±2 years ago.. when moved to React world :)

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109