I had read many articles about that async is not user friendly but in the following procedure everything messed up when I remove async because it needs one by one execution.
for (var k = 0; k < selectedValueArr.length - 1; k++) {
var value = selectedValueArr[k];
$.ajax({
type: "POST",
url: dm + "Services/AjaxService.asmx/GetCityCheck",
dataType: "json",
data: JSON.stringify({ code: value }),
contentType: "application/json; charset=utf-8",
async: false,
success: function(data) {
html += '<li style="height: 25px;"><div style="font-weight: bold; background-color: #91c8e2; padding: 3px 3px; font-size: 13px;">' + document.getElementById('stateName' + selectedValueArr[k]).innerHTML + '</div></li>';
var datafromServer = jQuery.parseJSON(data.d.toString());
$.each(datafromServer, function(key, value) {
html += '<li style="height: 18px; font-size: 12px;"><span pvalue="' + key + '"><input id="chkCity' + key + '" type="checkbox" title="' + value + '" style="border: 0px;" onchange="javascript:CityCheck(this)"><span title="' + value + '" id="cityName' + key + '">' + value + '</span></span></li>';
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
Can anyone tell me what is the replacement for async because it really hangs the browser…
Here’s an advice: instead of hammering your server with many AJAX requests in a loop it’s better to send all the data in a single AJAX request even if more data will transmit through the wire. It’s always better to minimize server roundtrips.
So get rid of the for loop and then send a single AJAX request:
and then modify your WebMethod so that it takes an array as input parameter and returns an array as output:
Notice that if your WebMethod returns directly a model instead of a string you don’t need to do any
jQuery.parseJSONinside your success callback but directly work withdata.d.And if you don’t want to follow my advice and kill your server with AJAX requests in a loop you will have to capture the
kindexer variable in a closure:Also notice how I am using the
contextparameter to the AJAX request in order to pass the value to the success callback. Then inside this success callback I have replaced theselectedValue[k]with this because the current context is now different. This is the proper way to pass information to the success callback from the outer context of the $.ajax call.