Im using jQuery UI autocomplete.
When i use a local variable as source it works.
var json = [
{type: "Utente",label: "Luca XXXX",url: "http://lvh.me:3000/users/4dde465add53e04e5c000001"},
{type: "Domanda",label: "Luca asdas adsfdsfdsf sdsd",url: "http://lvh.me:3000/questions/luca-asdas-adsfdsfdsf-sdsd"},
];
But when i return the same source from another file, it doesnt work. I find the JSON object in firebug and it seems the same as my local variable json.
The code is the following:
$( ".query-input" ).autocomplete({
minLength: 3,
source: "/search.json",
select: function( event, ui ) { window.location = ui.item.url }
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a href=" + item.url + ">"+ item.label +"</a><span>" + item.type + "</span>" )
.appendTo( ul );
};
This is search.json.erb file:
[<% @results.each do |r| %>
<% if r.is_a? User %>
{type: "Utente",label: <%= r.name.to_json.html_safe %>,url: <%= user_url(r.id).to_json.html_safe %>},
<% elsif r.is_a? Question %>
{type: "Domanda",label: <%= r.text.to_json.html_safe %>,url: <%= question_url(r.slug).to_json.html_safe %>},
<% elsif r.is_a? Topic %>
{type: "Argomento",label: <%= r.name.to_json.html_safe %>,url: <%= topic_path(r.id).to_json.html_safe %>},
<% end %>
<% end %>]
What is wrong?
The problem was the missed callback. Autocomplete needs a callback param to function properly.
The right search.json code is the following: