I am having one div.
<div id="test"></div>
Having few function.
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);
}
});
}
Function get call on different button click.
btn1.click(fun1())
btn2.click(fun2())
btn3.click(fun3())
When btn1,btn2, btn3 press immediately one after another, i can see div 'test' contain as first 'fun1' response after some time 'fun2' response and so on.
I know the reason, as my ajax response is very slow that's why it is happening.
When somebody click on btn1 and before getting response of fun1, press btn2. In this case i just want to load fun2 response. If fun2 is making delay want to show blank page.
I was thinking about killing remaining ajax request, on button press. But same time my other ajax request are also going, i don't want to kill those. So killing other ajax request will not work for me. What will be other solution.
OK you have two problems
1: you are firing multiple requests off when you really only want the last one to go be processed
2: each event updates the screen regardless of what else has happened
I suggest you attack these two problems separately.
First, add a call back function for your response. this will allow you to check conditions (such as 'has anything else happened?') before updating the page. This gives you the chance to throw the first to responses out.
Secondly, you need to deal with the sending of the multiple requests in the first place. You could either cancel them when the second button is clicked, (but they will still be processed on the server) OR: You could add a timer and not immediately send the request.
Start the timer when you click the button and then say 200ms? later, fire the request and process the response.
If you get another click before the 200ms has elapsed, forget the first timer and start a new one.
Alternatively you can prevent the user clicking buttons once a request has been sent by deactivating them and only reactivating once the response has been received.
eg: (bit crude with global vars 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With