Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell which ajax request failed?

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?

like image 898
Tony H Avatar asked Mar 30 '16 17:03

Tony H


People also ask

How do I know if AJAX request is successful?

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.

What is AJAX failure?

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.

How can AJAX call error be resolved?

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.


1 Answers

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);
});
like image 137
Joe Enos Avatar answered Sep 21 '22 19:09

Joe Enos