Search code examples
phpmysqljsonlivesearch

Ajax livesearch box


Here's the html and javascript code :

    $('document').ready(function(){
    $('input.typeahead').typeahead({
        name: 'typeahead',
        remote:'livesearch.php?key=%QUERY',
        limit : 10
    });
});
   
<html>
  <head>
    <title>Ajax Search Box using PHP and MySQL</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">        </script>
     <script src="typeahead.js"></script>
    </head>
    <body>
     <input type="text" name="typeahead">
</body>
</html>

The php file contains :

$key=$_GET['key'];
$array = array();
$query = $db->query(" SELECT * from product WHERE ProductName LIKE '%{$key}%' ") or die (mysql_error());
while($row = $query->fetch())
{
$array[] = $row['ProductName']; 
}
echo json_encode($array);

The php works absolutely fine. But I'm unable to get text in the input box


Solution

  • Use

    $('input[name=typeahead]')
    

    to apply the typeahead function to the input element.