Short version of Problem
Autocomplete works when the input string matches the result string, but not otherwise. The data are succesfully retreived from JSON.
Longer version
I want to dynamicly edit the source content of the autocomplete with JSON data.
The approach below works when the search string matches the first_name and last_name field.
But the JSON url returns more, e.g. with search on username it still returns correct data. But this is not shown in autocomplete, and my theory is that autocomplete UI forces the ‘input value’ to be the same as the ‘result value’.
JSON data returns:
[
{"pk": 1012912, "fields": {"first_name": "Barack", "last_name": "Obama"}},
{"pk": 1017519, "fields": {"first_name": "George", "last_name": "Bush"}}
]
The autocomplete code
As you can see the result set is set by the search function.
$('#search').autocomplete({
source: [],
search: function(event, ui){
results = [];
var json = jQuery.getJSON('http://jsondata.com?query='+event.target.value, function(data){
for (var i=0; i<data.length; i++){
results.push(data[i].fields.first_name + ' ' +data[i].fields.last_name);
};
}).success(function(){
$('#search').autocomplete('option', 'source', results);
//The following debug proves that the 'results' are correct, even on search for usernames
console.log(results);
});
},
});
If I search for ‘Barack Obama’ in the #search field, I get my results, no problem.
However, if say Barack Obama had the username ‘baracko’ and I search for his username, then I get the correct results from the JSON and in the results array (as I checked this with console.log) but the results are not shown.
Anyone have the idea why?
Solution for future googlers or those intrested
Thanks to some hints by ek_ny here is my new JSON:
[{ 'value' : 'Barack Obama'}, { 'value' : 'George Bush'}]
And here is the code:
$('#search').autocomplete({
source: function(req, res){
jQuery.getJSON('http://jsondata.com/?query='+req.term, req, function(data){
var results = [];
$.each(data, function(i, val){
results.push(val.value)
});
//Add results to callback
res(results);
});
},
});
I don’t know if this helps, but I set up my autocomplete a bit differently. I use the source property which allows me to control the call back to jQuery. My ajax call returns items in the form of [{“id”:1, “label”: “Annie Hall”,…..]. You could modify the results of the Ajax call however you want depending on how the data comes back from the server. Here is the code I use to call it.
One thing in your example which troubles me is the variable results, which seems to me to be a global variable. And we all know (in the words of Douglas Crockford) that global variable are evil.