Hello All,

I'm having a serious problem with AJAX in my web application that has our entire development team banging their head against the keyboard.
(Unfortunately, all that banging hasn't yielded a good answer, so I'm hoping one of the experts here have a possible solution!)

The core question is this:
How can I make sure ajax calls to the server have completed?

The problem we're having is that we have a page with a bunch of AJAX calls. The calls work perfectly and the page works well. The issue is that when we submit the form on the page, we get very inconsistent results. Sometimes everything works as expected and we're directed to the correct page. Other times, it seems like the AJAX calls are still

running and when the form is submitted it literally kicks us out of the application.

We tried to increment a counter when we start an ajax call and decrementing it when the ajax call finishes and then only submitting the form if that counter is zero, but that

sadly did not work.

Does anyone have any other ideas?

We're also open to using jQuery if that holds the answer.

Any and all help is greatly appreciated. And, if you help and you're ever in the Toronto area, I owe you a bunch of drinks! :)

You can use the readyState to wait for completion. See this thread for an example.


You need to somehow inhibit form submission until all AJAX calls have been satisfied.

Typically, you would do this with a function attached to the form's onsubmit event and control submission by returning false (to suppress) or true (to submit).

Your problem now becomes how to determine whether there are any unsatisfied AJAX calls.

Personally, I would create an object, var ajaxRequests ... (in a suitable scope, global if you have to), containing an array of references to all outstanding HTTPRequest objects. I think I would give the ajaxRequests object add() and remove() methods to help manage its array's elements, and a test() method to determine whether any ajax requests are unsatisfied.

As new HTTPRequests are instantiated, ajaxRequests.add() would be called (a simple Array.push() may suffice) and as each HTTPRequest successfully completes, ajaxRequests.remove(...) would be called (judicious use of Array.slice() ).

Using this approach, you shouldn't need to test readyStates (though that may well also be viable). The ajaxRequests.test() method would simply need to enquire whether the array of references was of zero length (return true ) or greater (return false ). The returned value would determine whether form submission should be allowed.

All this, pretty well off the cuff. I've not coded anything so there may well be a few wrinkles I've not considered.

Hope I'm making sense.