If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

XMLHttpRequest not working in Loop

Try to load details from sever side based on the provided prarams which are store in an array. Thus, there will be a loop, sending different request with different array element value. and I will use the return values (req.responseText) to replace some parts of the page.

The problem is that only the last request will be given the correct value. I tried to add "alert('');" to find out the problem, interesting thing is, if I close the alert window a little big slowly, all requests will be returned with correct values. However, if close them very quickly, only the last request working.

I thought it might be the reason that XMLHttpRequest need more time to process, and try to add setTimeout, not lucky, the same.

You're correct - it does need more time to process. That's the reason the last result is the only one that seems to provide the expected result. When the script hits the xmlhttp request, it continues processing on past it while the request is "out there" doing it's work. So, what's happening is that the subsequent requests are killing the previous requests.

One solution is to restructure your code to remove the loop. Another solution is to use a queue. I can't find the link for the one I've used, but you might try Googling for ajax request queue.

Queueing is slower than sending the requests asynchronously by either
a) attacking a reference to the handler and calling it using function.call(response), or
b) attaching an id to the request and having it send the id back with the response

Both methods allow you to send your requests simultaneously and receive them asap while still able to track which callbacks are being called by which request.