I'm trying to make a search input where a user can enter some keyword and it will autocomplete results from the database.
I've accomplished to make the search input to autocomplete and show results, the only thing missing now is to make it that when the user presses the name it will re-direct to the page for that result.
In this case I need to pass the results id as a parameter in the url.
HTML
<form action="" method="post">
<input type="text" name="clients" id="clients" data-provide="typeahead">
<input type="submit" name="clients_submit" value="Search">
</form>
jQuery
var clients = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('client_name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: './core/views/clients.php?query=%QUERY',
wildcard: '%QUERY'
}
});
clients.initialize();
$("#clients").typeahead({
hint: true,
highlight: true,
minLength: 2
},{
name: 'clients',
displayKey: 'client_name',
source: clients.ttAdapter()
});
PHP
header('Content-Type: application/json');
if(!isset($_GET['query'])){
echo json_encode([]);
exit();
}
$conn = new PDO('mysql:host=localhost;dbname=autocomplete;charset=utf8', "root", "root");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$clients = $conn->prepare("SELECT client_id, client_name FROM crm_clients WHERE client_name LIKE :query");
$clients->execute([
'query' => "{$_GET['query']}%"
]);
echo json_encode($clients->fetchAll());