Search code examples
ruby-on-railsajaxdrop-down-menuprototypejs

Rails 2.3.x Ajax call by using Prototype.js and "select" helper


Simply, I have 2 drop down lists. First one has the Accounts.

What I want to do is: Select an Account from the first drop down, take the id of the selected account, with that "id" take the information from the db and then fill the second drop down with "Ajax call".

Sounds simple but I couldn't build the relation.

Rails: 2.3.5 Js: Prototype.js ruby: 1.8.7

Drop down that I am trying to use (I am not really sure about what is going on with :onchange)

<%= select :account, :id
           @accounts.map{ |a| [ a.company a.id ] },
           { :include_blank => "--Select Account--"},
           :onchange => my_function() #I guess
%>

My Controller name: User, action: search_user

Question: How to send the selected account's id to my controller and then fill the second drop down, How should I modify the ":onchange=> my_function" Do I have to write any JS or helper function does that for me?

I search a lot but I find partial answers (because my rails version is very old I guess). So any answer would help a lot.

Solution:

Thanks to Santosh and Umut Sirin I figured it out. Here is how to do it:

1)Dropdown to make the ajax call

<%= select :account, :id
       @accounts.map{ |a| [ a.company a.id ] },
       { :include_blank => "--Select Account--"},
       :onchange => "my_function()" %>

2) Dropdown to be populated:

<select id="subaccounts" name="subaccount[id]"></select>

3) Prototype.js code to make the Ajax call and populate the 2nd dropdown:

<script type="text/javascript">
function my_function(){
var selectBox = $('account_id');

if(selectBox.selectedIndex === 0) {
    return;
}

var selectedValue = selectBox.options[selectBox.selectedIndex].value;
selectedValue = parseInt(selectedValue);

var subaccSelectBox = $('subaccounts');
new Ajax.Request('/controller_name/action_name_here/', {
    method: 'get',
    parameters: {id: selectedValue},
    onSuccess: function(transport) {
        var options = transport.responseJSON;
        for(var i = 0, len = options.length; i < len; i++) {
            var opt = document.createElement('option');
            opt.text = options[i].text;
            opt.value = options[i].value;
            subaccSelectBox.options.add(opt);
        }

    }
})

}

4) Controller action to return the JSON object to JS function:

def action_name_here
    id = params[:id]

    info= Model.find(#whatever you want to do wit "id")
    render :json => info
end

Solution

  • :onchange => "my_function(this)"

    function my_function(obj) {
      new Ajax.Request('/your/url', { parameters: obj.value })
    }