Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure AJAX requests called in a certain order get the response in the same order?

How to ensure AJAX requests called in a certain order get the response in the same order?

like image 908
airbai Avatar asked Mar 09 '11 04:03

airbai


2 Answers

First, keep in mind that the server itself might not return responses in the order the requests are received. Imagine if you fire a complicated ajax request first, and a simple on second (perhaps referencing some cached static data). The second request will probably return before the complicated one returns. You can see how this complicates things; if the order the requests are received is not the same as the order the responses come back, how can one make assurances?

You have some options:

1) You can make the requests synchronous instead of asynchronous. However, this will lock up the browser.

2) A better approach would be to chain the requests such that the next request only fires after the first is completed, by only firing the second request after the first returns.

As a note, if you find that you have 2 ajax operations that you need to chain, it might make sense to create a server endpoint to handle the 2 operations in one request. i.e., just make an ajax request to do everything you need.

like image 167
hvgotcodes Avatar answered Oct 17 '22 12:10

hvgotcodes


Another option is to have a counter in your Javascript code which is incremented every time this AJAX call is made. Then pass this value in your AJAX call and include that value in the response. This way you have a way of keeping track which order the responses should be in.

like image 38
Rono Avatar answered Oct 17 '22 10:10

Rono