I am using jQueryUI autocomplete to search a MySQL database. When user presses enter in the search field, I want to populate a div with the result(s) returned from DB.
The code works and does return an autocomplete list of suggestions.
However, I cannot understand how to use the JSON data returned in the select:
function, for example to access the title
and author
fields returned in the JSON object. See the indicated alert() line in the jQuery code sample.
ui.item
alerts as [object Object]
ui.item.title
alerts as undefined.
What else can I try?
Also, is item
the correct label to use? If so, why? Where does that come from (I used item
because it was consistently used in several examples I reviewed.)
My jQuery:
$('#srxbks').autocomplete({
source: "autocomplete_test.php",
minLength: 1,
select: function( event, ui ) {
alert('You chose: ' + ui.item); <=== THIS LINE <===
var out = 'Title: ' + ui.item.title + '<br>';
out += 'Author: ' + ui.item.author + '<br>';
$('.booksTableDIV').val(out);
}
});
My PHP:
<?php
include 'connect.php';
$term = strip_tags($_GET['term']);//retrieve search term sent by autocomplete
$qstring = "SELECT * FROM `books` WHERE `title` LIKE '%" .$term. "%'";
$query = mysql_query($qstring) or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
$row['title']=htmlentities(stripslashes($row['title']));
$row['bid']=(int)$row['bid'];
$row_set[] = $row['title'];
}
echo json_encode($row_set);