I am making requests in a loop, trying to accumulate the ID’s of the objects given back each time and send to the subsequent request so that they do not get returned a second time. However, the accumulator variable (obviously) is outside of .ajax() success callback, and is empty when I pass it through the data object of the call.
function fill_div(id, count) {
var rend = "";
var filler = $('#'+id);
for(i = 0; i < count; i++) {
$.ajax({'type':'POST',
'url':'/ads/render/',
'dataType':'json',
'data':"rendered="+rend}).success(function(data){
filler.append('<div id="' + data.adid + '"></div>');
rend+=data.mid.toString()+",";
_fill_ad(data);
});
}
}
When I look at the request in chrome’s inspector, the variable is there in the post data, but there is no value. I feel like I’m getting something messed up with scoping.
It looks like the issue here is that you’re expecting the returned values to be appended to the
rendstring in time for the next AJAX call. This isn’t going to happen, because making the calls is a synchronous process, but getting the return values is asynchronous. Instead of:the sequence will most like go something like:
In order to have each subsequent AJAX call aware of what’s been previously returned from the server, you’d have to chain the calls, so that the next AJAX call isn’t made until the previous call is completed. You could do this with recursion, like this: