jQuery part:
I have a jQuery UI 1.8 Autocomplete form that fetches remote JSON data from a Rails controller.
$('input#test').autocomplete({
source: function( request, response ) {
$.getJSON(
"<%= find_stuff_url(:format => :json) %>",
request,
function(data){
console.log(data);
function(data) {
$.map(data, function(item) {
return {
"label" : item.control_point.label,
"value" : item.control_point.geonames_uri
}
});
});
},
minLength: 2,
select: function( event, ui ) {
// ...
}
});
… what I get returned:
This Rails controller just returns an array of Objects (actually, ActiveRecord instances), serialized into JSON. I would like to use this data to populate the Autocomplete list. Right now, what I receive is an array of serialized ActiveRecord objects – for example one of these objects could be:
Object
control_point: Object
geonames_uri: "http://sws.geonames.org/5128581/"
label: "New York (US)"
lat: "40.7142691"
lng: "-74.0059729"
map_id: 1
name: "New York City"
What I need:
However, jQuery Autocomplete probably wants a JSON array of objects that carry id and label to populate its list — yet I don't have these. This is what the documentation says:
A response callback, which expects a single argument to contain the data to suggest to the user. This data […] can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties).
I don't quite understand what's meant by "String-Array or Object-Array with label/value/both" properties.
In this example, my output would be a list of those control_point Objects, shown like:
label: "New York (US)", value: <the geonames_uri>
label: "New York (Somewhere else)", value: <another geonames_uri>
…
I tried to adapt the code from the documentation using $.map, but it doesn't seem to work (i.e. the autocomplete shows nothing).
How do I pass an arbitrary JSON object to jQuery Autocomplete, so it shows a list of results? More explicitly: What do I have to put in function(data){}?
labelproperty should be shown to the user, and for example,geonames_uricould be the actual value behind it.