Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery ajax request, wait for latest request to finish

I have a textbox that for each time a user inputs a letter I make a search with an ajax request and show the result "live" for the user. Often when a user types the letters it takes longer time for the request to be made than for the user to input a new letter, hence a new request is made before the first one have ended. It would be much better if the first one could end before I do the next request. Is there a good way to only make a new request if the latest request have ended?

This is my jquery code:

$("#MyTextBox").change(function() {
    if (this.value.length > 2) {
        $.ajax({
            type: "GET",
            url: "http://www.domain.com/Service.svc/Search?keyword=" + this.value,
            dataType: "json",
            success: function(data) {
                //here I have some code that shows the result for the user
            }
        });
    }
});
like image 835
Martin Avatar asked Jan 05 '10 19:01

Martin


2 Answers

You could create a boolean that will hold true or false depending on if there is a request already happening. Set it to true when you start a request and set it back to false in your callback function.

var request_in_process = false;
$("#MyTextBox").change(function() {
    if (this.value.length > 2 && !request_in_process) {
        request_in_process = true;
        $.ajax({
            type: "GET",
            url: "http://www.domain.com/Service.svc/Search?keyword=" + this.value,
            dataType: "json",
            success: function(data) {
                request_in_process = false;
                //here I have some code that shows the result for the user
            }
        });
    }
});
like image 92
dl. Avatar answered Oct 17 '22 00:10

dl.


You can abort an AJAX request. Keep track of the request as a variable, and abort it before re-initiating the request.

var request = $.ajax({ ... });
request.abort();

This has the added advantage of being more responsive to user input. If the user has typed something more since the first request was initiated, he probably doesn't care about the first set of results anymore. Aborting and recreating the AJAX request means the user gets a better set of results back.

like image 24
ceejayoz Avatar answered Oct 17 '22 00:10

ceejayoz