mardi 22 décembre 2015

Like/dislike system using AJAX

I'm currently working on my first RoR project. For now i'd like to make integrate a like/dislike system into my application. I have some code, but it works just only when the page is reloaded. My goal is to make the ability to like/dislike a post without reloading the page(using Ajax, not the built-in one). So, here's my code, what is wrong here ?

My controller

def like
    @post=Post.find(params[:id])
    @post.increment!(:like)
    render :nothing => true, :status => 200
  end

  def dislike
    @post=Post.find(params[:id])
    @post.increment!(:dislike)
    render :nothing => true, :status => 200
  end

my view

<table>
  <% if @post.count!=0 %>
    <% @post.each do |p| %>
      <%if !p.text.nil?%>
        <tr data-post_id="<%= p.id %>">
       <td><b class="margin"><h4><%=p.text%></b></h4></td>
       <td>by <%= link_to p.user.username, profile_dashboard_path(p.user) %>&nbsp;&nbsp; </td>
       <td><span class="glyphicon glyphicon-thumbs-up likeAction"><%=  p.like %> </td>
       <td><span class="glyphicon glyphicon-thumbs-down dislikeAction"><%= p.dislike %> </td>
      <%end%>
    <% end %>
  <%else%>
    There's no posts yet, but you can add <%=link_to "one", create_a_post_dashboard_path(current_user)%>
  <%end%>
</table>

my js file, which is located in app/assets/javascripts/dashboard.js, so i dont have any js file with the name like.js.erb or dislike.js.erb(i'm not sure if i need them)

jQuery(function($) {
  $(".likeAction").click(function(){
    var current_post_tr = $(this).parents('tr')[0];
    $.ajax({
      url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/like',
        type: 'PUT',
        success: function(){
          $(".likeAction").hide().fadeIn();
          location.reload();
        }
     });
  });

  $(".dislikeAction").click(function(){
    var current_post_tr = $(this).parents('tr')[0];
    $.ajax({
      url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/dislike',
        type: 'PUT',
        success: function(){
          $(".dislikeAction").hide().fadeIn();
          location.reload();
        }
    });
  });
});

Aucun commentaire:

Enregistrer un commentaire