I'm having a trouble with ajax requests and server responses:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true,
error: function(){},
success: function(){},
complete: function(){alert('complete')}
});
}
The thing is - sometimes I get succes, when I should get it, but sometimes I can get 500 status, and it is normal and expected. The same ajax call works for correct requests, but fails for others. I want to display an error message if I get a 500 server error, but for some reason the ajax does not complete. Thus, neither error:
nor complete:
work. Maybe the reason for that is 'jsonp' datatype? Other datatypes do not work though. Can someone help please?
Or maybe give me an advice on how to detect server status any other way.
Make sure that you are accessing to your server. Maybe you are requesting in your server for an specific contentType
(like application/json
) and you are not using that property into your ajax call.
As you requested, to show any message if get a error (400, 404, 500...), you can use my custom function for ajax error responses:
function onErrorFunc(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status + '
Status text: ' + status +
'
Error thrown: ' + errorText);
}
Usage:
$.ajax({
//some options
error: onErrorFunc
});
Please, show us what error thrown your server.
jsonp requests do not trigger error callbacks by design, therefore there is no way for you to catch the error with javascript. I suggest instead implementing an error handler on your server that detects a jsonp request and returns jsonp that indicates an error has occured rather than a 500 status code.
Note that error:
is deprecated as of 1.8 and is not called for JSONP however I wonder if you might have success using the Promise functionality introduced with 1.5 for deferred
http://api.jquery.com/category/deferred-object/ as:
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
Example for your code:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true
}).done(function(data, textStatus, jqXHR){ //replace success
alert(textStatus);
}).always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { // replace complete
alert(textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) { // replace error
alert(errorThrown);
});
Thank you all for comments. Jquery .ajax really does not give errors on jsonp requests. The way to get error messages was to implement the jquery-jsonp plugin: https://github.com/jaubourg/jquery-jsonp