order of ajax post requests getting mixed up
I have a page where the user sends data (via ajax) to a php page, which inputs it to a database. However, occasionally, the requests are getting out of order when I check the database.
Basically, the user inputs events as they occur and hit submit to send it off to the database. Occasionally, the user will record 2 events before sending it, in which case, the 2 events are sent 1 at a time. This case is when they get switched occasionally.
Here is the relevant code.
i = 0;
while (event[i]) {
var post_data = //post data for event[i]
$.ajax({
type: "POST",
url: "save_event.php",
data: post_data,
});
event.splice(0,1);
}
Event[] is an array containing the events the user is submitting. Each event is an object with various properties. Usually, there is only 1 object in the array, but sometimes there are 2. I removed the part where I do the post_data because it spans 3 lines.
Maybe half of the time that there are 2 events, they get reversed in the database. Is there a way I can eliminat开发者_如何学Pythone that? Or does it depend entirely on the length of time it takes the server to process, and occasionally, it will finish the 2nd one before it is done processing the 1st?
As AJAX requests are sent asynchronously and in parallel this will entirely depend on the browser and the processing time of the server. You could add the async: false
option but this will freeze the browser during the requests as they will no longer be asynchronous.
I would recommend you adding an order column to your database.
var post_data = { order: i, ... };
Another option would be to send a single AJAX request containing all the data.
If order matters then either send the sequence number with it and figure it out in the server, or send all the events at the same time.
精彩评论