Reputation: 36373
I need some suggestions here or maybe some explanations. I have a jquery ajax call,
$.ajax({
type: "GET",
url: base_url+'/ajax/fetch/counts/',
dataType: 'json',
data: {},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
},
success: display_counts
});
It's working fine. My success
callback fires correctly with response. But, what I noticed is that my error
callback is fired every time, even when my call returns success status 200. In the above error
callback, I see that object xhr.status
is 200.
Can anybody explain what's wrong, or what is happening here? error
callback is supposed to fire only when I have 404 or maybe a non-200 response. Are my assumptions correct?
Thanks.
Upvotes: 41
Views: 109499
Reputation: 53462
Error callback is called on http errors, but also if JSON parsing on the response fails. This is what's probably happening if response code is 200 but you still are thrown to error callback.
Upvotes: 36
Reputation: 73906
Just an suggestion, try using the $.ajaxSetup() to get the correct error like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
Upvotes: 39
Reputation: 11070
I'm not a jQuery expert, but I know that bwith Prototype.js, the AJAX error handler fires if the request is successful but the success
handler causes an an error. Is that the same in jQuery? You could test if this is what's happening by putting the entire contents of display_counts
in a try..catch block.
Upvotes: 1
Reputation: 29658
A few things I can think of:
cache: false
.Upvotes: 2
Reputation: 11110
A recent question had similar problem with json
jquery requests, try removing surrounding ()
from your json response.
Upvotes: 2