I'm trying to use autocomplete in jquery, and it works with the demo data, but I haven't been able to make it work with my own data source. I'm trying to write a mailer where the user just enters a few letters of a person's name, and the contacts database helps autocomplete so that the corresponding emails show up in the "To" field.
I've included the following files:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
My jQuery code in document.load is below:
$(function() {
function log( message ) {
$('#to').append(message);
console.log(message);
}
$( "#search" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item? ui.item.email : "NO" );
}
});
});
And my HTML is:
<div class='ui-widget'><input type='text' class='medium' id='search' /></div> <br />
To:<br />
<div class='ui-widget'> <textarea type='text' style='width:80%; height:24px;' id='to' class='ui-widget-content'></textarea></div>
The result of search.php is fine as far as json is considered, here's a sample of the output when the letters "Ahmed" are pressed:
[{"email":"saddi@yahoo.com","name":"Ahmed Qasim"},{"email":"aaaab@alangari.com.sa","name":"Ahmed Abbas"},{"email":"mokhlef@yahoo.com","name":"Ahmed Sahdi"}]
I know I'm getting this response from search.php because I check Firebug and see it, but it doesn't show up below the search input field... Instead, what does show up is just a stump of a list... as in the image below.
But this exact same thing worked as expected when I used the demo code here: demo Why doesn't the list show up properly? Is there a limit on how much data can be displayed? I've pasted only 3 entries from the JSON output I got, but there were tens.
What you are returning from server contains email
and name
fields, jquery ui needs an value
and label
field.
[{"label":"Ahmed Abbas", value: "Ahmed Abbas"}]
label
is what you see on autocomplete list, and value
is the value you will get when you select an item.
I think keune has the correct diagnosis. If you don't want to change the output of search.php, you could do something like this:
$( "#search" ).autocomplete({
source: function (request, response) {
$.ajax({
url: "search.php",
type: "POST",
dataType: "json",
data: { searchText: myQuery, maxResults: 10 },
success: function(data) {
var mappedData = $.map(data,
function(item) {
return {
label: item.name,
value: item.email,
id: item.email
};
});
response(mappedData);
}
});
}, ....