Is there a way to pass variables from beforeSend to success functions in the jQuery .ajax function? -
the problem
when working ajax query remote api, asynchronous nature of request comes whenever completes. problem when have make iterative calls same api different criteria, don't know response coming back.
the question: possible pass variable
sample code: (simplified)
n=5; for(i=0; < n; i++) { $.ajax({ url: someurl, method: post, // don't want have use async: false, that's bad // async: false, data: json.stringify(somedata), beforesend: function(){ console.log("starting request #"+i) }, error: function(err, code, text) { alert("something went wrong: \n\n" + code + ": " + text); }, success: function(response) { console.log("response request #"+i) console.log(response) } }) }
the problem comes in final success function: should see is:
starting request #0 starting request #1 starting request #2 starting request #3 starting request #4 response request #2 [object] response request #1 [object] response request #4 [object] response request #0 [object] response request #3 [object]
what see is:
starting request #0 starting request #1 starting request #2 starting request #3 starting request #4 response request #4 [object] response request #4 [object] response request #4 [object] response request #4 [object] response request #4 [object]
this important not because care logs being right, because actual version needs able reconcile responses sent. don't want go synchronous on this, because it'll slow, annoying, , possibly time out.
as mentioned in comments, special case of more common mistake closures in loops. since value of i
have changed time success
runs, you'll want store (by calling helper function outside loop makes ajax request) or bind i
success function. example:
for (var = 0; < 5; i++) { $.ajax({ url: '/url', success: function (i, response) { console.log("response request #"+i); console.log(response); }.bind(window, i) }); }
Comments
Post a Comment