lundi 21 décembre 2015

Refreshing an element without reloading the page with ajax

i wanted to make a like/dislike ability on my web application using ajax, but i'm afraid, that my method works not fine, so, what am i doing wrong ?(i want to make it with the clear ajax, not with ne built-in Rails Ajax) So, here's my code

my dashboard.js:

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().fadeOut();
          location.reload();
        }
    });
  });
});

My methods in 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", dashboard_posts_create_a_post_path%>
  <%end%>
</table>

I do not understand this theme clearly, so i'd appreciate your help

Aucun commentaire:

Enregistrer un commentaire