I have an auto complete search field which as the user types a name, th results are shown in the dropdown.
This all works fine, and shows the data as it should.
I am waiting to make each result a link however, so when the results are shown the user can click on the correct name and it will take them to their profile.
See script below:
search.php
$searchTerm = $_GET['term'];
$sql = mysql_query ("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE '{$searchTerm}%' OR name_first LIKE '{$searchTerm}%' OR employee_id LIKE '{$searchTerm}%'");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = array (
'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
Upon selecting the correct user, I would like the user to de directed to page.php?id=$employee_id
Is this possible?
JavaScript
JavaScript
$(function() {
$( "#employees" ).autocomplete({
source: 'search.php'
});
});
# Answer 1
As requested:
PHP:
$pdo = new \PDO('mysql:host=localhost;dbname=test', $user, $pass);
$searchTerm = $_GET['term'];
$stmt = $pdo->prepare("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE :search OR name_first LIKE :search OR employee_id LIKE :search");
$stmt->execute([':search' => $searchTerm.'%']);
$array = [];
while (false !== ($row = $stmt->fetch())) {
$array[] = [
'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',
'id' => $row['id'],
];
}
echo json_encode($array);
JavaScript:
$( "#employees" ).autocomplete({
source: 'search.php',
select: function( event, ui ) {
window.location.href = 'page.php?id='+ui.item.id;
}
});
Fiddle with console.log instead of location change: https://jsfiddle.net/dLe4a83x/
# Answer 2
Here you can use JQuery UI library to make navigation in autocomplete search Autocomplete search in PHP and Mysql. Here is the working code:
HTML form :
Javascript code:
`
$(function() {
$("#dd_user_input").autocomplete({
source: "global_search.php?cityId=28",
minLength: 2,
select: function(event, ui) {
var getUrl = ui.item.id;
if(getUrl != '#') {
location.href = getUrl;
}
},
html: true,
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
`
Here location href is mentioned so user can navigate upon clicking this link.