Reputation: 732
How can I find out what parameters were passed to an (asynchronous) jQuery AJAX request after it is complete?
Basically, I am firing a bunch of AJAX requests with different id passed as a parameter and displaying the results to the user when each of them finishes. Now, if the request is successful, I can pass the id back in the result of the request. But, if the request fails, I don't know which request failed, i.e. for what id was that request.
Example (javascript/jQuery):
for(var i=0; i < 10; i++ ) {
$.ajax({
type: "GET",
url: "get-results.php",
data: { 'id': i },
success: function(data, textStatus, xmlReq) {
data = $.parseJSON(data);
$("#result" + data.id).html(data.result);
},
error: function(xmlReq, textStatus, errorThrown) {
var id= ???;
$("#result" + id).html('error bla bla');
}
});
}
Upvotes: 2
Views: 2518
Reputation: 2061
You need to capture the current value of i
for the error
function. And you capture with a closure. So:
error: function(id) {
return function(xmlReq, textStatus, errorThrown) {
$("#result" + id).html('error bla bla');
};
}(i)
That is error
is the result of immediately calling an anonymous function passing in the current value of i
.
Upvotes: 2
Reputation: 227280
$.ajaxError
gives you the data send via the AJAX call.
.ajaxError(handler(event, XMLHttpRequest, ajaxOptions, thrownError))
The ajaxOptions
object contains all the options that can be set via $.ajax
So, instead of using the error:
option in $.ajax
, use $.ajaxError
.
$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError){
if(ajaxOptions.url.indexOf('get-results.php') != -1){
var data = ajaxOptions.data; // this is a string: 'id=1¶m2=4'
// to get the ID, you need to parse this
}
});
Upvotes: 3
Reputation: 385274
Use the fact that Javascript supports closures, and just write the variable name (but be careful to copy it inside the for
block scope so that it does not change):
for(var i=0; i < 10; i++ ) {
var INDEX = i;
$.ajax({
type: "GET",
url: "get-results.php",
data: { 'id': i },
success: function(data, textStatus, xmlReq) {
data = $.parseJSON(data);
$("#result" + data.id).html(data.result);
},
error: function(xmlReq, textStatus, errorThrown) {
var id = INDEX;
$("#result" + id).html('error bla bla');
}
});
}
I believe that this is what you want.
Upvotes: 2
Reputation: 114417
You'll need to pass them back with your response.
Upvotes: 1