4

I am trying to use select2 with my rails application but cannot get the result displayed in my views. I see the correct json coming in chrome console but cannot get the result displayed in the dropdown ...

Could you please help me ?

Thanks :

Controllers :

def friends
  if params[:term]
    @users = User.where{ ( (first_name =~ my{"%#{params[:term]}%"}) | (last_name =~ my{"%#{params[:term]}%"}) | ( ((first_name.op('||', ' ')).op('||',last_name)) =~ my{"%#{params[:term]}%"}) | ( ((last_name.op('||', ' ')).op('||',first_name)) =~ my{"%#{params[:term]}%"}) ) & ( adult==false ) }
  end
  respond_to do |format|  
    format.html
    format.json { render :json =>{:results => @users.to_json(only: [:id, :first_name, :last_name]) }}
  end
end

My Javascript :

$("#teen_search").select2({
  placeholder: "Search for a teen",
  minimumInputLength: 2,
  ajax: {
    url: "/friends.json",
    dataType:'json',
    data: function (search, page) {
      return {
        term: search, // search term
        page_limit: 10,
      };
    },

    results: function (data, page) {
      return data;
    }
  },
  dropdownCssClass: "bigdrop"
});

I cannot figure what's wrong, thanks for your help

I just edited the controller render_to json and the results in js to fix an error in the chrome console, I know I am close but still cannot get my user first_name and last_name displayed in the field ...

Brandan
  • 14,735
  • 3
  • 56
  • 71
Jeremy B
  • 911
  • 7
  • 20
  • what means you dont get the correct result? – BvuRVKyUVlViVIc7 Nov 20 '12 at 13:56
  • Nothing is displayed in the box, only the text searching, but I do see a json file with the data in my chrome console – Jeremy B Nov 20 '12 at 14:29
  • Ok so I believe now the issue is with the json, select2 require if i'm correct to get a json with id and text and nothing else how could I do that ? I want to display my select2 box like the moviebox in the select2 example with pictures and text thanks ! – Jeremy B Nov 20 '12 at 15:45

2 Answers2

5

So I ended up doing that :

User_Controller :

def friends
if params[:term]
    @users = User.where{ ( (first_name =~ my{"%#{params[:term]}%"}) | (last_name =~ my{"%#{params[:term]}%"}) | ( ((first_name.op('||', ' ')).op('||',last_name)) =~ my{"%#{params[:term]}%"}) | ( ((last_name.op('||', ' ')).op('||',first_name)) =~ my{"%#{params[:term]}%"}) ) & ( adult==false ) }.select("id,first_name,last_name,avatar,uid")
    @user = @users.paginate(:page => params[:page], :per_page => params[:page_limit])
end
respond_to do |format|  
    format.html
    format.json { 
      render :json => {
        :users => @user,
        :total => @users.count,
        :links => { :self => @user.current_page , :next => @user.next_page}
    } 
  }
end
end

In the JS Script :

    $(document).ready(function() {
    $("#teens_select2").select2({
        placeholder: "Search for a teen",
        minimumInputLength: 1,
        ajax: {
            url: "/friends.json",
            dataType: 'json',
            quietMillis: 300,
            data: function (search, page) {
                return {
                    term: search,
                    page_limit: 10,
                    page: page,
                };
            },
            results: function (data, page) {
            var more = (page * 10) < data.total;                
              return {results: data.users, more: more};
            }
        },
        formatResult: movieFormatResult,
        formatSelection: movieFormatSelection, 
        dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
    });
});

Also formatResult and formatSelection are configured like that before you load the script :

    function movieFormatResult(user) {
    var markup = "<table class='movie-result'><tr>";
    if ( user.uid !== null) {
         markup += "<td class='movie-image'><img src='" + user.avatar + "'/></td>";
    }
    else if (user.uid == null) {
        var gravatar = user.avatar + 40
         markup += "<td class='movie-image'><img src='" + gravatar + "'/></td>";
     }

    markup += "<td class='movie-info'><div class='movie-title'>" + user.first_name +' '+ user.last_name + "</div>";

    markup += "</td></tr></table>"
    return markup;
}

function movieFormatSelection(user) {
    return (user.first_name + ' ' + user.last_name);
}

And the in the view :

<input type ="hidden" id="teens_select2"></input>

I really hope it can be useful.

Jeremy B
  • 911
  • 7
  • 20
2

Just change 'jsonp' by 'json' in the dataType attribute.

p1nox
  • 623
  • 1
  • 7
  • 13
  • Well i did that to test and I have an error in the chrome console : Uncaught TypeError: Cannot read property 'length' of undefined but I also added a console.log(data) in the result function and I do see my objects ... thanks it's still not working but seems to be on a good way – Jeremy B Nov 20 '12 at 15:09
  • I fixed I believe another part of the controller and the js in the question but still cannot get an answer, however the searching now disappear so I believe I am close ... – Jeremy B Nov 20 '12 at 15:28