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);
});
}
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);
});
}
200 OK
? Doesn't .done
check for that for you? What problem are you facing with this code?
– gen_Eric
Commented
Apr 29, 2016 at 19:06
async: false
? I wouldn't suggest using that because it will lock up the user's browser until the call is done.
– gen_Eric
Commented
Apr 29, 2016 at 19:07
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 plete:
are called in either case.from official docs:
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
http://api.jquery./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 :)