tags:

views:

86

answers:

5

I would like to make sure there is only one AJAX request going on (for a user) at a time. This is what I tried:

var ajaxFinished = 1;

$('#selector').keyup(function() {

    if (ajaxFinished == 1) {

        ajaxFinished = 0;

        $.get('test.php', { par : "par" }, function(data) {

            // do stuff with data
            ajaxFinished = 1;

        });
    }

});

But the problem is the AJAX request gets executed only once now even though I activate the event multiple times.

+3  A: 

Could it be that when you $.get an error is occurring and ajaxFinished is never being reset to 1?

You may want to use $.ajax rather than $.get. $.ajax will let you catch success and error events.

Corey Downie
A: 

A queue of requests and a manager?

glebm
That was the answer box, the question box is http://stackoverflow.com/questions/ask
Question Mark
+2  A: 

I think Corey has it nailed. Another possibility: Could it be that the code block you quote is inside another function we don't see? Then it could be that ajaxFinished is out of scope - correct me if I'm wrong, my knowledge of JS scoping and anonymous functions is not perfect. In that case, you would have to remove the "var" or declare it in the body.

Pekka
Yeah, that was it, it was inside an object method, so I had to use this keyword.
Richard Knop
+1  A: 

if i were coding that function i would split it up and call a timeout

var autocomplete_timeout;

$('#selector').keyup(function() {

    if(autocomplete)
       clearTimeout(autocomplete_timeout);
    autocomplete_timeout = setTimeout(300, "autocomplete('"+ this.val() +"');");
});

function autocomplete(param1, param2){
        $.get('test.php', { par : "par" }, function(data) {

            // do stuff with data
            ajaxFinished = 1;

        });
}

Something along those lines to buffer the ajax call until 300ms after the user has stopped typing

Question Mark
+2  A: 

I guess ajaxFinished should be a global variable. Remove the var keyword. Try:

ajaxFinished = 1;
Shailesh Kumar