I'm sending out a bunch of getJSON() requests to a remote server (to fetch images), and I'd like to display the responses (images) in the same order in which I send the requests. Problem is, AJAX is asynchronous, so the responses come in whatever order they want - usually all mixed up.
I could queue them or make them synchronous - only sending out one request at a time - but that will severely limit the performance.
So is there a way I can identify which response belongs to which request when the responses come back? I was thinking you could put an "id" variable into the JSON callback parameter (e.g. callback=response03) and then somehow parse that callback function name when the response arrives (thus grabbing the id, "03"). But probably not.
My code is something like this:
// Send off requests for each keyword string
$.each($imageRequests, function() {
$request = this;
$url = "http://www.example.com/api?q="+$url;
$.getJSON($url, function($response) {
if($response.data.items) {
$.each($response.data.items, function($i, $data) {
$imgUrl = $data.url;
$("#imageList").append($imgUrl);
});
}
});
});
I've tried creating a bunch of new divs to hold the returned images, thinking I could populate the divs with their respective images, but that didn't work either.
// Create new div with unique id using line number
$i = 0;
$.each($lines, function() {
$newDiv = '<div id="img_'+$i+'"></div>';
$("#imageList").append($newDiv);
$i++;
});
// Then do the same as the code above but shove the responses into "#img_$i" using the iterator variable to "keep track" (which didn't work).
I've searched and although there are similar questions about AJAX on here, none are as specific as what I'm looking for.
Thanks.
EDIT - heading to bed just now but I will be back on tomorrow - if you can, please check back. I really appreciate the help. :)