0

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.

Sebin
  • 1,044
  • 1
  • 8
  • 21
  • Does your ajax request hits the controller action i.e index? What are the params do you get in that action? – Nikita Singh May 19 '16 at 07:16
  • It does, but for testing AJAX I changed the index action to: def index ` if request.xhr? @user = User.all render :json => @user else @user = User.all end end In this case I can access a user with result[0].name ` – user6196039 May 19 '16 at 08:23
  • Sorry, for some reason the formatting didn't work. – user6196039 May 19 '16 at 08:23

1 Answers1

0

Here I have modified the source part in your script. You need to have an AJAX callback which calls the response function; passing the array that contains items to display. Reference

<script>
    $(function() {

        $('#auto').autocomplete({
            minLength: 2,
            source: function (request, response) {
                jQuery.get("/users.json", {
                    query: request.term
                }, function (data) {
                    response(data);
                });
            },
            focus: function(event, ui) {
                $('#auto').val(ui.item.name);
                return false;
            },
            select: function(event, ui) {
                $('#auto').val(ui.item.name);
                return false;
            }
        })
    });
</script>

Controller:

def index
  @users = User.order(:name).where("name LIKE ?", "%#{params[:query]}%")
  respond_to do |format|
    format.html
    format.json { 
      render json: @users.map(&:name)
    }
  end
end
Community
  • 1
  • 1
Sebin
  • 1,044
  • 1
  • 8
  • 21
  • Thank you for the code. It seems like the AJAX call is working as I don't see that error message in the console. The input field is however not showing any suggestions when I type something. There might be some issue with the controller as it looks like it's not searching the typed term. – user6196039 May 19 '16 at 13:36
  • Started GET "/users.json?query=John" for 125.253.101.55 at 2016-05-19 13:34:46 +0000 Cannot render console from 125.253.101.55! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 Processing by UsersController#index as JSON Parameters: {"query"=>"John"} User Load (0.8ms) SELECT "users".* FROM "users" WHERE (name LIKE '''%%''') ORDER BY "users"."name" ASC Completed 200 OK in 5ms (Views: 0.5ms | ActiveRecord: 0.8ms) – user6196039 May 19 '16 at 13:37
  • `@users = User.order(:name).where("name LIKE ?", "%#{params[:query]}%")` Can you try with this? – Sebin May 19 '16 at 13:38
  • What's it now in console? – Sebin May 20 '16 at 02:07
  • It's not showing anything in the console. The server logs say this: Processing by UsersController#index as JSON Parameters: {"query"=>"John"} User Load (0.3ms) SELECT "users".* FROM "users" WHERE (name LIKE '%John%') ORDER BY "users"."name" ASC Completed 200 OK in 7ms (Views: 0.3ms | ActiveRecord: 0.8ms) – user6196039 May 20 '16 at 04:12
  • Try removing the focus and select portions and check if it works. – Sebin May 20 '16 at 04:42
  • Thank you so much, removing the focus and select portions solved the problem. With "$('#auto').val(data.users) " now all Users that match the input are showed. The issue is that the whole array of results is displayed in the input field. What can I do to show individual inputs in a list below the input field? – user6196039 May 20 '16 at 05:45
  • Have you included the css required for autocomplete? – Sebin May 20 '16 at 05:47
  • No, I haven't included any CSS so far. I tried this approach but it didn't work: $("#auto").append("
  • " + data.users + "
  • "); – user6196039 May 20 '16 at 05:48
  • You are not using the gem? Please refer: https://github.com/joliss/jquery-ui-rails – Sebin May 20 '16 at 05:50
  • Yes, I'm using the gem. – user6196039 May 20 '16 at 06:23
  • Are you sure you have `*= require jquery-ui/autocomplete` inside application.css? – Sebin May 20 '16 at 06:32
  • Yes, it's inside application.css. All the search results are displayed in the input field, separated by commas. – user6196039 May 20 '16 at 10:23