user3240928
user3240928

Reputation: 555

How do I post to Rails using Ajax?

I am trying to pass a variable through jQuery using the POST method, storing it to a controller, then using that same variable in the Rails HTML to query a table.

It does not seem like it is passing the variable to the controller.

jQuery:

var id = 1;

$.post("http://localhost:3000/teamplayers", {'ids': ids});

Teamplayers controller:

def index
   @teamplayers = Teamplayer.all
   @ids = params[:id]
end

Rails HTML:

<select id = "test3" style= float:right size= 10>
<% Teamplayer.find_each(:conditions => "teamid = @ids") do |tp| %>
    <option> <%#[email protected] %></option>
    <option>Players on team 1</option>
<% end %>
</select>

Also, I tried to use the following Ajax method but it posted my page back into the tag I assigned it to.

Ajax:

$(document).ready(function(){
    $("button").click(function(){
      $.ajax({url:"http://localhost:3000/teamplayers",success:function(result){
        $('#div1').text(result);
   }});
 });
});

What is wrong with the way I am using POST or the Ajax?

Upvotes: 0

Views: 68

Answers (2)

Fred Willmore
Fred Willmore

Reputation: 4614

It looks like you just have a variable naming problem - rename 'id' to 'ids' where needed:

jQuery:

var ids = 1;
$.post("http://localhost:3000/teamplayers", {'ids': ids}); 

Teamplayers Controller:

@ids = params[:ids]

Upvotes: 0

DiegoSalazar
DiegoSalazar

Reputation: 13531

One of your first problems is in the controller: you are incorrectly asking for params[:id] when you should be asking for params[:ids] since you pass it in from jQuery land via {'ids': ids}. You also need to pass in a success handler function to the $.post function so that you can handle the response and make something ajaxy happen.

Once you've instantiated @ids properly you can pass it directly to the model's find method:

<% Teamplayer.find(@ids) do |tp| %>

And that will find all the Teamplayers with those ids. Here you could be taking advantage of Rail's form helpers to generate that HTML select list. Instead of this:

<select id = "test3" style= float:right size= 10>
<% Teamplayer.find_each(:conditions => "teamid = @ids") do |tp| %>
    <option> <%#[email protected] %></option>
    <option>Players on team 1</option>
<% end %>
</select>

Do this:

<%= select_tag "test3", options_from_collection_for_select(Teamplayer.find(@ids), "id", "name") %>

Note that the last argument to options_from_collection_for_select is "name" as an example only. You should change that to the name of the field in your Teamplayer table that you want to use as text in the option tag, I'm guessing it would be teamid.

Lastly, I'm not sure what you're trying to do with that last ajax call. Hopefully the aforementioned will fix your original problem.

Upvotes: 2

Related Questions