Reputation: 347
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?
Upvotes: 8
Views: 806
Reputation: 40393
Another alternative would be write to the XHR object itself, and then it's there for you in the fail
method, and wouldn't require you to use a closure:
var obj = { a: 1 };
var xhr = $.post("/product/update", obj)
.done(function (data) {})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(this.data); // The raw string a=1 which was posted
console.log(jqXHR.postData); // The {a: 1} javascript object
});
xhr.postData = obj;
Upvotes: 2
Reputation: 40393
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);
});
Upvotes: 9