I've been trying since a couple of days to create an auto-complete input which is connected to my rails database but haven't managed to make it working. My code in the view looks like this:
<script>
$(function() {
$('#auto').autocomplete({
minLength: 2,
source: '/users.json',
focus: function(event, ui) {
$('#auto').val(ui.item.name);
return false;
},
select: function(event, ui) {
$('#auto').val(ui.item.name);
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item)
.append( "<a>" + item.name + "</a>" )
.appendTo( ul );
console.log(ui.item.name);
};
});
</script>
My controller looks like this:
def index
@users = User.order(:name).where("name LIKE ?", "'%# {params[:term]}%'")
respond_to do |format|
format.html
format.json {
render json: @users.map(&:name)
}
end
end
The issue I'm having is that nothing is returned to my autocomplete input and I see a non-defined message in the console. I thought it there could be an issue with my source and the ui.item... part in the code and tried different variations, but nothing worked. The weird thing is that it works if I change the source to a local array of values. I also tried to check if there is a problem with AJAX and created a test script which works fine.
<script>
$('h3').click(function(){
$.ajax({
type:'GET',
url:"/users",
dataType:'json',
success:function(result) {
console.log(result)
},
});
});
</script>
I really don't know what to do anymore. Would be great if someone can help me with this.