Dingo Dingo - 1 day ago 4
jQuery Question

Issue with Ajax changing image Rails

I have a rails app and am using the

acts_as_votable
gem for likes/unlikes.

A Post can be liked or unliked.

I am using ajax to update the like count without reloading the page and it is working fine, although I am trying to make it so that when the 'like' button is clicked, the image source changes.

Currently this only works for the 'unlike' button but for some reason not for the like button.

Here is my
_votes
partial:

<% if current_user.liked? post %>
<%= link_to unlike_post_path(post), remote: true, method: :put, class: 'unlike' do %>
<%= image_tag("/assets/like.png", id: "like") %>
<% end %>
<% else %>
<%= link_to like_post_path(post), remote: true, method: :put, class: 'like' do %>
<%= image_tag("/assets/heart.png", id: "heart") %>
<% end %>
<% end %>


Here is my
index.html.erb
(minified):

<span id="likes_<%= post.id %>">
<%= post.cached_votes_up %>
<% if post.cached_votes_up == 1 %>
like
<% else %>
likes
<% end %>
</span>


Here is my
like.js.erb
:

$('.like').bind('ajax:success', function() {
$('#likes_<%= @post.id %>').html('<%=escape_javascript @post.get_upvotes.size.to_s %>');
$("#heart").attr("src", "/assets/like.png");
});


Here is my
unlike.js.erb
:

$('.unlike').bind('ajax:success', function() {
$('#likes_<%= @post.id %>').html('<%=escape_javascript @post.get_upvotes.size.to_s %>');
$("#like").attr("src", "/assets/heart.png");
});


As you can see, both ajax files are similar, but only the
unlike.js.erb
one actually changes the image.

I have made sure all the image paths are correct and everything, I am just not sure why the
#heart
image isnt changing to the
like.png
image?

Answer

Since you have many posts and the id may be in two or more places,

$("#heart").attr("src", "/assets/like.png"); may not work fine

You should refer each image with a specific id

Instead, use $("#heart_<%= @post.id %>").attr("src", "/assets/like.png");

your html be like:

<%= link_to like_post_path(post), remote: true, method: :put, class: 'like' do %>
    <%= image_tag("/assets/heart.png", id: "heart_#{post.id}") %>
<% end %>

your js.erb is:

$('.like').bind('ajax:success', function() {
    $('#likes_<%= @post.id %>').html('<%=escape_javascript @post.get_upvotes.size.to_s %>');
    $("#heart_<%= @post.id %>").attr("src", "/assets/like.png");
});
Comments