I have a CSHTML page where I need to make three separate Ajax calls in order, and each one has to wait until the previous one(s) have returned before running. I want to put a message on the webpage showing which of the calls is being handled at that particular time.
However, using async: false
does not work as the second call will start before the first one is completed, and using "async: true" does not work as the page does not update until all three calls are completed, at which point there is no need to display a progress message.
This is what I mean:
function doFullAnalysis() {
doAnalysisStep(1);
doAnalysisStep(2);
doAnalysisStep(3);
showTheResults();
}
function doAnalysisStep(runType) {
$(button_div).html("Type " + runType + " processing...");
$.ajax({
type: "GET",
url: '@Url.Action("AnalyzeDataRun", "DataHandler.svc")',
data: {"RunType": runType},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (HelpRequest, ErrorCode, TheError) {
resultString = "Error running the analysis:<br />" + TheError;
$(item_div).html(resultString);
},
async: false;
});
}
As written, doFullAnalysis will call doAnalysisStep three times, but will not update block button_div until all three calls to doAnalysisStep() and the call to showTheResults() are completed. However, if I remove "async: false", then the second call is done before the first one is completed, which is a Bad Thing as the second call depends on the results of the first one.
I have also tried:
var isRunning = false;
function doFullAnalysis() {
doAnalysisStep(1);
while (isRunning);
doAnalysisStep(2);
while (isRunning);
doAnalysisStep(3);
while (isRunning);
showTheResults();
}
function doAnalysisStep(runType) {
$(button_div).html("Type " + runType + " processing...");
isRunning = true;
$.ajax({
type: "GET",
url: '@Url.Action("AnalyzeDataRun", "DataHandler.svc")',
data: {"RunType": runType},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (HelpRequest, ErrorCode, TheError) {
resultString = "Error running the analysis:<br />" + TheError;
$(item_div).html(resultString);
},
complete: function() {
isRunning = false;
}
});
}
However, this puts it in what appears to be an infinite loop; I think it is too busy handling the first while (isRunning)
loop to let isRunning = false
in the complete block execute.
Is there a way to handle updating the page between synchronous requests?