rahul891
rahul891

Reputation: 89

How to ensure latest search results are fetched in a live Ajax search

I am trying to build a live AJAX search box. I am using keyup() function to trigger the search api with the current value of the input box as the search-text. However since the search api calls are asynchronous there is no guarantee that the final api call will be the one that is rendered as it may finish before the previous api calls.

For example, if I enter "free" in the input box there will be four api calls with "search_text" = f,fr,fre & free. The search?search_text=free call may finish faster than the search?search_text=fre api call even though it was fired later. How do I ensure that the results from the final api call (in this case search?search_text=free) are always rendered in the results page?

I have seen solutions where they advise to fire a request only for a stable query, i.e. when the user has stopped typing (for say 200ms or so). However I think despite that there is still no guarantee that on firing 2 successive search queries (say with a time delay >=200ms) results from the second one will always complete last. What is the best way to build this ajax live search?

<input type="text" id="search" name="search" class="form-control input-lg" />

$('#search').keyup(function() {
  $.ajax({
      type: "POST",
      url: "/search/",
      data: {
        'search_text' : $('#search').val(),
      },
      success: searchSuccess,
    });
  });

function searchSuccess(data) {
  // logic to render search results to web page
}

Upvotes: 0

Views: 240

Answers (1)

Leonid
Leonid

Reputation: 804

let counter = 0; // ADDING A COUNTER
$('#search').keyup(function() {
// INCREASING THE COUNTER VALUE AND STORE IT INTO A LOCAL VARIABLE
  let cur = ++counter; 
  $.ajax({
      type: "POST",
      url: "/search/",
      data: {
        'search_text' : $('#search').val(),
      },
      success: data => {
// CHECKING IF THE LOCAL VARIABLE AND COUNTER ARE EQUAL
        if(cur == counter){
// IF EQUAL: IT IS THE LAST QUERY
          searchSuccess(data);
        } else {
// IF NOT: DON'T DO ANYTHING
          return false;
        }
       }
    });
  });

function searchSuccess(data) {
  // logic to render search results to web page
}

Upvotes: 1

Related Questions