I have a search box in my application that uses the jQuery UI Autocomplete plugin to display a list of users in the system based on last name, from a remote data source.
When a user is clicked from the autocomplete list, I’d like the browser to redirect to that user’s individual page (based on a GET parameter). However, the GET parameter for the user page is the user “id”, different from the display values “last_name, first_name”.
How do I push the user “id” to the GET parameter while still displaying the first and last names values in the dropdown?
I have seen similar questions asked on here, but none while using a remote data source.
Any help you can provide, would be amazing!
Javascript:
$(document).ready(function() {
$( ".user_autocomplete" ).autocomplete({
source: "../../db/users.php",
minLength: 0,
focus: function (event, ui) {
this.value = ui.item.value;
},
}).bind( "autocompleteselect", function(event, ui) {
window.location.href = "/users/index.php?id=" + this.value;
});
});
Remote Data Source (users.php)
<?php
$return_arr = array();
if(isset($_GET['term'])) {
$mysearchString = $_GET['term'];
}
$sth = $dbh->query("SELECT id, first_name, last_name FROM users
WHERE last_name LIKE '$mysearchString%'
ORDER BY last_name");
while ($row = $sth->fetch ()) {
$row_array = $row['last_name'].', '.$row['first_name'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
To have an ID that is different from the (display) VALUE, you must return a JSON encoded array of objects like this:
You can then use
ui.item.idto retrieve the selected ID.NOTE: You can also provide a “label” property that is different from the “value” property. Here’s the information from the documentation:
EDIT:
I’m not a PHP guy, but I imagine the code to create the JSON array would be something like this: