title: Aborting $.post() / responsive search results
body: <p>I have the following kludgey code;</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;input type="search" id="search_box" /&gt;
  &lt;div id="search_results"&gt;&lt;/div&gt;
  </code></pre>
  
  <p><strong>JS</strong></p>
  
  <pre><code>var search_timeout,
      search_xhr;
  $("#search_box").bind("textchange", function(){
      clearTimeout(search_timeout); search_xhr.abort();
      search_term = $(this).val();
      search_results = $("#search_results");
  
      if(search_term == "") {
          if(search_results.is(":visible"))
              search_results.stop().hide("blind", 200);
      } else {
          if(search_results.is(":hidden"))
              search_results.stop().show("blind", 200);
      }
  
      search_timeout = setTimeout(function () {
          search_xhr = $.post("search.php", {
              q: search_term
          }, function(data){
              search_results.html(data);
          });
      }, 100);
  });
  </code></pre>
  
  <p>(uses the <a href="http://www.zurb.com/playground/jquery-text-change-custom-event" rel="nofollow noreferrer">textchange plugin by Zurb</a>)</p>
  
  <p>The problem I had with my original more simple code was that it was horribly unresponsive. Results would appear seconds later, especially when typed slower, or when Backspace was used, etc.</p>
  
  <p>I made all this, and the situation isn't much better. Requests pile up.</p>
  
  <p>My original intention is to use <code>.abort()</code> to cancel out whatever previous request is still running as the textchange event is fired again (as per <a href="https://stackoverflow.com/a/446626/951402">446594</a>). This doesn't work, as I get repeated errors like this in console;</p>
  
  <pre><code>Uncaught TypeError: Cannot call method 'abort' of undefined
  </code></pre>
  
  <p>How can I make <code>.abort()</code> work in my case?</p>
  
  <p>Furthermore, is this approach the best way to fetch 'realtime' search results? Much like Facebook's search bar, which gives results as the user types, and seems to be very quick on its feet.</p>