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?
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?
-
Do you mean that you are calling this multiple times with different values for
formPostData
and you don't know which call has failed? – LinuxDisciple Commented Mar 30, 2016 at 17:55 -
2
What do you mean "which request failed"? You are only showing code for one request. If you hit the
.fail()
function, you know that it is thepost
thatfail
is connected to that failed. – Scott Marcus Commented Mar 30, 2016 at 17:55
2 Answers
Reset to default 9The 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);
});
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;