I am sending a few getJSON () requests to a remote server (for receiving images) and I would like to display the responses (images) in the same order in which I send the requests. The problem is that AJAX is asynchronous, so the responses come in whatever order they need - usually everything is mixed up.
I could queue them up or make them synchronous - only sending one request at a time, but that would severely limit performance.
So, is there a way to determine which response belongs to the request when the responses are returned? I thought you could put the variable "id" in the JSON callback parameter (for example, callback = response03), and then somehow parse that name of the callback function when receiving the response (thus capturing the identifier "03"). But probably not.
My code looks 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 tried to create a bunch of new divs to store the returned images, thinking that I could fill the divs with their corresponding 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 searched and although there are similar questions about AJAX here, none of them are as specific as what I am looking for.
Thanks.
EDIT - go to bed just now, but I'll be back tomorrow - if you can, come back. I really appreciate the help. :)