0

I'm updating search results as the user types the search term.

When 2 ajax calls happen, sometimes the last one data_response is brought back first. I need to make sure this doesn't happen.

This is my code:

function filterCities(search) {
    $.ajax({type:'GET',url:'/ventas/theme/citiesContainer.php',data: "search=" + search,
    success:function(data_response){
        results.innerHTML = data_response;
        }});
    }

How do I cancell previous instances of the same request when I make a new one?

lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

3 Answers3

3

This is a solution with a simple counter:

<script>
var counter = 0;
function filterCities(search,c) {
    $.ajax({type:'GET',url:'/results.php',data: "search=" + search,
    success:function(data_response){
        if(c == counter) { // Only update if it's data_response from last call
            results.innerHTML = data_response;
            }
        }});
    }
</script>

<input type="text" onkeyup="counter++; filterCities(this.value,counter);">
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
2

You could transmit a counter in the URL, and send the counter back, and just ignore the results if they aren't from the most current iteration. Much like a sequence number in UDP packets.

crush
  • 16,713
  • 9
  • 59
  • 100
0

You need to look for an ajax queue plugin (or write one)

How do I go about getting the Ajax Queue plugin working in jQuery 1.3?

just search some more here on SO and google for "jquery ajax queue"

Community
  • 1
  • 1
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100