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);
});
}
Share
Improve this question
asked Apr 29, 2016 at 19:05
espresso_coffeeespresso_coffee
6,12012 gold badges96 silver badges220 bronze badges
7
-
Why do you need to check for
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 -
P.S. Why are you using
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 - I do not know if .done actually check for that. In the past I was putting if statement inside of success. – espresso_coffee Commented Apr 29, 2016 at 19:07
- What would you remend to use instead? – espresso_coffee Commented Apr 29, 2016 at 19:08
- Instead of async: false? Or I do not need that. – espresso_coffee Commented Apr 29, 2016 at 19:15
2 Answers
Reset to default 4You don't need to check. The various callbacks are called under the following conditions:
.done()
orsuccess:
are called when the AJAX call is successful..fail()
orerror:
are called when there's an error (either from the server or in the jQuery code that parses the response)..always()
orplete:
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 :)