Levi Levi - 1 month ago 4
Ajax Question

Ajax Search as user types

I have a search feature that I am trying to implement. I would like the user to be able to type their "Search" and ajax fires as the user types to assist with finding their "Search".

This is what I have; This is working but requires the user to hit search.

jQuery(document).ready(function($) {
// Let us trigger the search if the user clicks on the search button.
$('.btnSearch').click(function(){
makeAjaxRequest();
});
// Let us trigger the search if the user submit the form by an enter.
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});

function makeAjaxRequest() {
$.ajax({
url: 'searchAction.php',
data: {name: $('input#name').val()},
type: 'get',
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});

Answer

You need to bind your function to the keyup-event of the input field.

Adding the following line of code inside the $(document).ready()-function

$( "#name" ).keyup(makeAjaxRequest);

could do the trick for you.

To only perform the AJAX request on a minimum length of three chars in the input field, you can change your makeAjaxRequest() function like so:

function makeAjaxRequest() {
  if($('input#name').val().length > 2) {
    $.ajax({
      url: 'searchAction.php',
      data: {name: $('input#name').val()},
      type: 'get',
      success: function(response) {
        $('table#resultTable tbody').html(response);
      }
    });
  }
}
Comments