简体   繁体   中英

Correct way to use Ajax with rails

I am trying to add ajax to a voting system but having difficulty targeting individual elements with jQuery. This is what i have so far:

Vote Link in index action

<%= link_to post_votes_path(post), :method => 'post', :remote => true do %>
<span class="score"><%= post.votes.size %></span>
<% end %>

Create action in Vote controller

def create
@post = Post.find(params[:post_id])
@vote = @post.votes.create

respond_to do |format|
  format.html { redirect_to root_url }
  format.js 
end
end

jQuery in votes#create view (create.js.erb)

$('.score').html("I voted"); 

Trouble is when i click the link to vote it changes the html for all posts not just the post i tried voting on. Dont have much experience with jQuery so i cant help but think i am missing something obvious. Any ideas ?

all your spans have the .score class. that's the reason for all be changed.

This is a possible solution. Change in your html:

<span class="score p_<%= post.id%>"><%= post.votes.size %></span>

And then change in your create.js.erb

$('.score.p_<%= @post.id %>').html("I voted");

I typically just use JQuery's $.post. I am using asp.net, but assume rails will work with that as well.

$.post("/someurltoyouraction", {myval:val},function(data){
  // do stuff after post
});

This will produce an Ajax post request. You can define your post parameters in the {myval:val} object to match your requirements. It's essentially a key value definition based object {key:value}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM