recently I developed a project were I send multiple ajax requests at a single aspx page. I also put a timer were this request is happening with interval 5 seconds.
Everything seems to work fine until suddenly the responses mix up. I know that I could do the same thing with one request, but I wonder why this is happening. I looked around the internet but I can’t find any solution yet. I now actually adopted this style of coding like making one request with multiple results, but I wonder and I really want to know how to make multiple ajax request were the response will not mix up.
This is my sample Code:
$(document).ready(function () {
var a = setInterval("request1()", 5000);
var b = setInterval("request2()", 5000);
});
function request1() {
$.ajax({
url: 'ajaxhandler.aspx?method=method1' ,
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=utf-8');
},
success: function (data) {
alert(data);
}
});
}
function request2() {
$.ajax({
url: 'ajaxhandler.aspx?method=method2' ,
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=utf-8');
},
success: function (data) {
alert(data);
}
});
}
If you need the requests to happen in order, you shouldn’t be using AJAX (the first “a” is for “asynchronous”).
To address this you can call request2() in the callback for the “success” of your first request.