Say I have this:
for( i = 0; i < 10; i++ )
{
$.ajax({
type: "POST",
url: "geocode-items.php",
async: true,
data: {
key: i
},
success: function( data )
{
// data returns the index I passed into the script with the data property.
},
error( a, b, c )
{
alert( i ); // this obviously won't work
}
});
}
alert( i ); in the error section is not going to alert the correct index. Whereas in the success I can be passing back the key I put in to the geocode-items.php script, I can’t pass anything back in the error section.
Do you know how to reference the original data sent through the request when firing the error method?
something like this.data.key? so I can report back an error for the specific object I’m stuck on? Rather than having to write some generic “there was an error code but I don’t know where”
you should read something about the scopes of javascript and about closures.
the value
iis the same for each error callback in your case and because ajax is async theiis 10 for all of them.javascript only has functions based scopes and no block based scopes.
What you can do is create an anonymous function where you pass your value to
(function(param1) { } )(value)this function is called immediately. the parameters of the functions are then bound to that function call.