jquery allows for success failure and error responses. How can i return a failure or error manually along with a string that describes the failuer or error?
The function specified by the ajaxError() function is called when the request fails or generates the errors. We can use the fail() callback function as well on the JavaScript promise object( the jqXHR object return by the $. ajax() function) to run the specific function on the ajax request fail.
The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds. The function takes three parameters, namely: The data returned from the server, formatted according to the dataType parameter, or the dataFilter callback function.
Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.
Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.
It has become somewhat of a convention to utilize a simple JSON envelope to report failures that occurred on the server side (that are not HTTP errors).
The flickr api provides a typical packaging example:
look at the bottom of this page for success and failure examples
So in the case of an Ajax call to the flickr API, in your success callback you would check the returning data for success/failure
$.ajax({
//...
success: function(data) {
if(data.stat == 'fail') {
//data.code + data.message contain details that could be used here
}
else {
//do success stuff here
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With