I have this code block to post a HTTP request via jquery .post() method.
$.post("/product/update", formPostData)
.done(function (data) {
// success
alert(data.product_id + ' was updated!');
})
.fail(function (data) {
// fail, but which request?
});
When it is successful it is easy to know which request we are dealing with, since the json returned by the server has the 'product_id'
that I need.
But if it fails due to an error in which the server is not responsive, a connectivity problem for example, how can I tell which request has failed?
The data
object has no clues because it only contains the server response.
How can I pass a value to the .fail()
handler so I can determine which request has failed?
The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.
Introduction to jQuery ajax fail. The jQuery ajax fail is an ajax event which is only called if the request fails. The AJAX fail is a global event that triggered on the document to call handler function, which may be listening. The ajax fail can be performed with the help of the ajaxError() function.
The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.
The this
object is useful here. You should be able to parse this.data
and get your post information from there:
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(this.data);
});
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