views:

44

answers:

2

I have a couple of buttons that users can click to load content with jQuery's $.ajax. All the buttons load the content into the same div tag. The problem is that if users click multiple times quickly, the content can flash several times before landing on the correct content.

What workaround do I have for this? I was thinking of something similar to .net's SyncLock feature, but in javascript/jQuery. The ideal solution would be to cancel requests currently in the queue and start the new one.

One thing to note is that there might be multiple unrelated ajax requests going on so I can't clear all requests, just ones relating to this one div tag.

+3  A: 

Clearing/cancelling the request is an expensive task so uness you really need it dont do it. It also wont stop the execution on the server side, just close the httprequest.

What you should do is set a "lock" and lock and unlock it accordingly. Something like:

var working = false;

function startAjax() {
    working = true;
    // do ajax and wait for callback()
}

function callback() {
    working = false;
}

In the buttons .click() make sure you check if working before actual execution:

$("#thebutton1, #thebutton2").click(function() {
    if(working) {
        alert("Im in the middle of something");
    } else {
        // execute...
    }
});
Ariel
I like approach because I can notify the user that a request is being executed already.
Paul Knopf
A: 

What you could do is to have the click event of all buttons that send output to the same div disable the button. Then in the AJAX callback, once you've processed the response, you can re-enable them all.

Tony Miller