rjhilgefort
8/14/2013 - 7:10 PM

Type Ahead Ajax

Requirements

  • bootstrap with typeahead
  • jquery

Explanation

This will use bootstrap with typeahead to create an autocomplete search. It shouldn't search until user is done their thought. Aka - fast typers. Right now set to 300ms.

Also caches content from server so you don't make the same call over and over again.

RJH Edits

  • Made this into a reusable function.
  • Store the cache result in association with the $obj passed into the function.
function typeaheadAjax ($obj, path) 
{
  // use this hash to cache search results
  $obj.query_cache = {};
  
  $obj.typeahead({
    source:function (query, process)
    {
      // if query is in cache use cached return
      if($obj.query_cache[query]){
        return process($obj.query_cache[query]);
      }
      
      //if searching is defined, it hasn't been executed yet but the user typed something else
      if( typeof searching != "undefined") {
        clearTimeout(searching);
        process([]);
      }

      //define a timeout to wait 300ms before searching
      searching = setTimeout(function() 
      {
        return $.getJSON(
          path,
          { query: query },
          function (data) {
            // save result to cache, remove next line if you don't want to use cache
            $obj.query_cache[query] = data;
            // only search if stop typing for 300ms aka fast typers
            return process(data);
          }
        );
      }, 300);
    }
  });
}