I have jQuery UI autocomplete input with AJAX source where I want to show the label and not the id; but my code shows both when the search results come back. How can I show just the label?
PHP:
<?php
require_once '../php/db_conx.php';
$req = "SELECT *
FROM ads
WHERE bbookname LIKE '%" . strtolower(mysql_real_escape_string($_REQUEST['term'])) . "%' ";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$return = array(
'label' => $row['bbookname'] . ' ' . $row['bbookschool'],
'value' => $row['adid']
);
}
echo json_encode($return);
?>
jQuery/AJAX:
$("#BooksSearchInput").autocomplete({
source: '../Search/BP_Books_Search.php',
minLength: 1,
autoFocus: false,
select: function(event, ui) {
var SearchBookVal = (ui.item.value)
$.ajax({
type: "POST",
data: {
data: SearchBookVal
},
url: "../php/SearchBooks_results.php"
}).done(function(feedback) {
$('#booksads').html(feedback)
});
}
});
Please note that I do need the adid to be available in the JavaScript callback, as I use this to reference the result.
You have got a couple of things wrong in your code.
First of all, the following line in the PHP script:
$return = array(...)
means the return variable will be overwritten on each iteration and result will always be an array with one item (or a PHP warning and the string null if no matching rows were found). To fix:
$return = array();
while ($row = mysql_fetch_array($query)) {
$return[] = array(
"label" => $row["bbookname"] . " " . $row["bbookschool"],
"value" => $row["adid"],
// you can add additional keys without causing problems
"feedback" => $row["feedback"]
);
}
echo json_encode($return);
Secondly, to display the label in the textbox you can use the code for onFocus and onSelect from this answer:
// ...
focus: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
},
select: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
$("#booksads").html(ui.item.feedback);
}
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With