Reputation: 805
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 ?
Upvotes: 0
Views: 75
Reputation: 7779
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");
Upvotes: 1
Reputation: 39248
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}
Upvotes: 0