2

I'm trying to figure out how to pass data with ajax using a checkbox in Rails 3.2.11. I have the following line in my view

<%= check_box_tag(
        "institution_ids_#{inst.name.gsub(" ", "")}",
          inst.id,
          false,
        data: {
          remote: true,
          institution_id: inst.id}) %>

When I change the status of the checkbox, I can see that the controller is correctly getting called (specifically the index method of the controller, which is what I want as that is the view I'm in), however, I cannot seem to access the institution_id variable from the params hash on the controller. Can someone please explain how I use ajax to pass data from the view to the controller within a checkbox. I thought the remote: true function would correctly call the controller (which is does) with the additional parameters that I set (which it doesn't).

1 Answer 1

5

Why don't you use jquery to make Ajax call.

<%= check_box_tag( "institution_ids_#{inst.name.gsub(" ", "")}", inst.id, false %>

<script>
     $('#checkbox_id').change(function(){
        $.get('controller/action?inst_id='+$(this).val(), function(data,status){
            if(status == 'success'){
              alert(data)
             }
        })
     })
   </script>

In controller:

def action
   inst_id = params[:inst_id]
   #do something
   render :text => "success" 
end
Sign up to request clarification or add additional context in comments.

3 Comments

I figured I could do something like this. I have a lot of checkboxes, and I figured this would be more readable if I can do everything inline. Is that just not possible?
try using like this: :data => { :remote => true, :url => { :action => action_name, :institution_id => inst.id} }
So the above didn't work, but this did data: {remote: true, url: url_for(action: :index, institution_id: inst.id), institution_id: inst.id}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.