I am attempting to make consecuitve async ajax calls in order to paint user’s schedules into a HTML table via jQuery.
Each response returns a JSON serialized DataSet containing two tables: one of scheduled events and the other contains user info.
The problem I am having is that the user info seems to get mixed up with user events. That is, sometimes the user onfo doesn’t
change for different responses so the scheduled events are tied to an incorrect user. If I set the AJAX async property to false, all is well.
The whole point is to display the schedules one by one as the data is returned instead of making the page freeze until all data is returned.
Is there a way to ensure that the first JAX call completes before the subsequent call executes?
(Perhaps my understanding of setting async to false is incorrrect. Doesn’t it mean that all data is harvested before code execution continues?)
Here is my current approach:
// When page loads
$(document).ready(function () {
// Get date range
debugger;
//GetStartDate(), GetEndDate() populates date range
//PopulateParams() does that for remaining parameters
$.when(GetStartDate(), GetEndDate())
.then(function () {
PopulateParams();
GetUserSchedule();
})
.fail(function () {
failureAlertMsg();
})
});
// Returns schedule for each person listed in between selected start and end dates
function GetUserSchedule() {
for (var i = 0; i < arrRequests.length; i++) {
$.when(
// Ajax call to web method, passing in string
$.ajax({
type: "POST",
url: URL/default.aspx/GetSchedules",
data: arrRequests[i], // example data: {"UserId":"6115","startDate":"\"7/1/2011\"","endDate":"\"7/31/2011\MoreVals: Vals} contentType: "application/json",
dataType: "json",
success: SuccessFunction,
error: function (d) { alert('Failed' + d.responseText + '\nPlease refresh page to try again or contact administrator'); }
})
)
.then(function () {
}
);
}
}
// On successful completion of call to web method, paint schedules into HTML table for each user
function SuccessFunction(data) {
if (data != null && data.d != null && data.d.Temp != null) {
// Calls a bunch of functions to paint schedule onto HTML table
// Data contains two tables: one contains user info and the other contains rows of info for each event for user
// at times, the user info is not the correct user or the events are not correct for user
}
Here is how I solved the issue. Hopefully it will help someone else. There may be some typos… this is just meant to show general idea. I called my GetData method recursively:
This general outline permits each async call to complete before processing the next call. In other words, the group of async calls don’t execute all at once and thus, don’t hammer the web method responsible for returning data. In my case, I was returning a dataset containing two tables and the tables returned were inconsistently accurate unless I set the async flag to false (not acceptable for my purpose), or followed the oulined approach.