Monday, June 3, 2024
152
rated 0 times [  156] [ 4]  / answers: 1 / hits: 25628  / 13 Years ago, fri, september 30, 2011, 12:00:00

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);
}

});
}

More From » asp.net-ajax

 Answers
43

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.



function request1() {
$.ajax({
url: 'ajaxhandler.aspx?method=method1' ,
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=utf-8');
},
success: function (data) {
request2();
}

});
}

[#89842] Thursday, September 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinarnoldp

Total Points: 10
Total Questions: 122
Total Answers: 109

Location: Spain
Member since Thu, Dec 23, 2021
3 Years ago
;