Hi could some one please take a look at this and let me know where I'm going wrong. I am trying to get jQuery UI autocomplete to work. this is my code: This is search.php
include "db_connect.php";
$search = $_GET['term'];
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$rows = array();
while ($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
print json_encode($rows);
?>
this is my javascript inline script
<script type="text/javascript">
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "./search.php",
minLength: 3
});
});
</script>
and this is the 'auto' div
<div id="searchTxtFieldDiv">
<p><input type="text" id="auto" /></p>
</div>
When I look at the call using firebug I see that search.php is returning
[{"Title":"Sin City"}]
jQuery is just displaying UNDEFINED any ideas??
Initialize Autocomplete: The autocomplete() function initialize the Autocomplete plugin. Specify the selector ID/class ( #skill_input ) of the input field element where autocomplete feature will be attached. Specify the local or remote source ( fetchData. php ) to retrieve the data for auto-suggestions.
Have a look at jquery ui autocomplete documentation. The JSON you are returning does not match what the autocomplete is looking for. The object you return must have properties named label or value (or both).
You can try the following options:
Change the JSON being returned to include the label/value properties such as:
[{"label":"Sin City"}]
From the examples it also seems to use the id property. I believe the above is the minimum requirement for the autocomplete to display a list of values. I think you can also return an array of strings and it will render it in exactly the same way as the above.
[ "Sin City", "Etc" ]
Change the private _renderItem function for the autocomplete to use your custom properties as shown in this autocomplete example (untested):
$( "#project" ).autocomplete({
source: "./search.php",
minLength: 3
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.Title )
.appendTo( ul );
};
This is a bit more flexible but much uglier imho.
@Shaun Thanks mate, sometimes you just need someone to point out the obvious. The way I finally got it to work was
include "db_connect.php";
$search = protect($_GET['term']);
$result = mysql_query("SELECT Title FROM `movie` WHERE `Title` LIKE '%$search%' ORDER BY Title ASC") or die('Something went wrong');
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['Title'].'"}';
}
$json .= ']';
echo $json;
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