How to handle ajax slow response to div sharing with multiple functions
I have one div.
<div id="test"></div> Several functions.
fun1() { $('#test').html(''); $.ajax(function(){ url : abc/index; success : function(response){ $('#test').html(response); } }); } fun2() { $('#test').html(''); $.ajax(function(){ url : abc/getDetail; success : function(response){ $('#test').html(response); } }); } fun3() { $('#test').html(''); $.ajax(function(){ url : abc/getUser; success : function(response){ $('#test').html(response); } }); } The function receives a call each time the button is pressed.
btn1.click(fun1()) btn2.click(fun2()) btn3.click(fun3()) When btn1, btn2, btn3 immediately click one after the other, I see that the div 'test' contains, as the first answer, fun1 after a while, "fun2", etc.
I know the reason, since my ajax answer is very slow, why is it happening.
When someone clicks on btn1 and before receiving the answer fun1, press btn2. In this case, I just want to load the fun2 answer. If fun2 delays, want to show a blank page.
I was thinking about killing the remaining ajax request when I clicked a button. But at the same time, my other ajax request is also coming, I don't want to kill them. So killing another ajax request will not work for me. What will be the other solution.
Ok you have two problems
1: you fire multiple requests when you really want the latter to be processed.
2: each event updates the screen no matter what else happened
I suggest you attack these two problems separately.
First add a callback function for your answer. this will allow you to check the conditions (for example, “did something else happen?”) before refreshing the page. This gives you a chance to throw away the first answers.
Secondly, you need to deal with sending multiple requests in the first place. You can either cancel them by pressing the second button (but they will still be processed on the server) OR: you can add a timer and not immediately send a request.
Start the timer when you press the button and then say 200 ms? later, run the request and process the response.
If you get another click before 200 ms, start the first timer and start a new one.
Alternatively, you can prevent the user from clicking on the buttons after sending the request by deactivating them and only after activating the response.
for example: (bit coarse with global characters that I know)
var btnLastPressed =0 fun1() { btnLastPressed = 1; $('#test').html(''); $.ajax(function(){ url : abc/index; success : function(response) { finished(1,response);} }); } function finished(btn, response){ if(btnLastPressed==1){ $('#test').html(response); } }