0 Replies - 1337 Views - Last Post: 21 January 2016 - 10:17 PM Rate Topic: -----

#1 user54321  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 21-January 16

Using ajax and jquery to update a partial in RoR

Posted 21 January 2016 - 10:17 PM

I've had this issue for days and been unable to figure it out... I have 'Like' and 'Unlike' button. When a user "likes" a post, the updates should occur in the data base and then the button should flip to "unlike". Everything works on the backend - the database updates just fine, however the button never switches from "Like" to "Unlike". If I manually refresh the page it will be switched, but it doesn't happen without the refresh. I do not have any errors logged or in the console.


<%= form_for(current_user.likes.build, remote: true) do |f| %>
<div><%= hidden_field_tag :post_id, post.id %></div>
<%= f.submit "Like", class: "btn btn-primary" %>
<% end %>


<%= form_for(current_user.likes.find_by_post_id(post.id),
html: {method: :delete },
remote: true) do |f| %>
<%= f. submit "Unlike", class: "btn" %>
<% end %>

These are rendered through: post/_post.html.erb

<div id="like_form">
    <% if post.does_user_like(post.id, current_user.id) %>
        <%= render 'shared/unlike', :post => post %>
    <% else %>                  
        <%= render 'shared/like', :post => post %>
    <% end %>


$("#like_form").html("<%= escape_javascript(render('shared/unlike', :post => @post)) %>");

Likes Controller
def create
      user = current_user    
      post = post.find(params[:post_id])
      @post = post
      Like.create(post_id: post.id, user_id: user.id)     
      respond_to do |format|
            format.html { redirect_to request.referrer || root_url }

I was able to get it to sort of work by adding location.reload(); to create.js.erb file. This refreshes the whole page though and there is a delay between clicking the button and the change. I've also tried to use replaceWith instead of html is the create.js.erb file.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1