my Ajax calls don’t seem to be asynchronous when wrapped inside a .each loop, instead they seem to wait for each to finish before calling the next one ..
MVC C#:
[HttpPost]
public JsonResult DoActionGetNextStep(JSONSubmission Submission)
{
SomeStruct body = new SomeStruct();
DateTime start = DateTime.Now;
try
{
System.Threading.Thread.Sleep(5000);
body.html= "There, done";
}
catch (Exception e)
{
body.html= "There was an error: "+e.Message;
}
TimeSpan s = DateTime.Now - start;
ast.Html = body.html+ "<p> c# took " +s.Seconds +"s</p>";
return Json(body);
}
JQuery:
function DoActions(targets) {
$(targets).each(function () { DoAction($(this)); });
}
function DoAction(target) {
var parent = $(target).parents('div.actionReplaceable');
var JSONSubmission = { Data : "somedata" };
var Submission = JSON.stringify(JSONSubmission, null, 2);
$.ajax({
type: 'POST',
url: '/Main/DoActionGetNextStep',
data: Submission,
async: true,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (Result) {
var html = Result.html;
$(parent).html(html);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$(parent).html("JQuery Error: " + textStatus + "\n" + errorThrown);
}
});
}
This ends up taking 25 seconds for 5 elements, each of them reporting that their call took 5 seconds. I thought ajax calls were asynchronous, so this operation should take 5 seconds total? Both server and browser are running on my localhost. Can anyone spot what I’m missing?
Your requests should be asynchronous. Check with
console.login the appropriate places to see when things happen.targetparameter. jQuery setsthiscorrectly for callback functions.targetparameter you just need to pass the function reference to.each().dataType: 'json'is wrong.async: trueis superfluous unless you configured the global Ajax options to beasync: false. Which I hope you did not.