Reputation: 667
i'd like to make a like/dislike ability on my RoR application. How can i make it via Ajax-requests ?
dislike and like - are integer how can i make an Ajax-request, than i can send the data of what i want to increment either "like" or "dislike" counter in my methods
I have a table with posts :
<table>
<%if @post.count!=0%>
<%@post.each do |p|%>
<%if !p.text.nil?%>
<tr>
<td><b class="margin"><h4><%=p.text%></b></h4></td>
<td>by <%=p.user.username%> </td>
<td><span class="glyphicon glyphicon-thumbs-up likeAction"><%= link_to p.like, dashboard_like_path, :remote => true, :id => 'likecount' %> </td>
<td><span class="glyphicon glyphicon-thumbs-down"><%= link_to p.dislike, dashboard_dislike_path, :remote => true, :id => 'dislikecount' %> </td>
<%end%>
<% end %>
<%else%>
There's no posts yet, but you can add <%=link_to "one", dashboard_posts_create_a_post_path%>
<%end%>
</table>
My js file
#app/views/dashboard/view.js
$('#likecount').text(@post.like);
$('#dislikecount').text(@post.dislike);
my methods in controller :
def like
@post.increment!(:like)
respond_to do |format|
format.html
format.js
end
end
def dislike
@post.increment!(:dislike)
respond_to do |format|
format.html
format.js
end
end
My dashboard.js in assets/javascripts
jQuery(function($) {
$("likeAction").click(function(){
$.ajax({
url: dashboard_like_path,
type: 'POST',
success: function(){
$('#linkcount').text(data);
}
error: function(error){
alert(error);
}
});
});
});
Upvotes: 0
Views: 627
Reputation: 1098
You can use Rails remote => true function for making ajax call. You can see more details here.
Now answer of your question,
i. create link for like & dislike like:
<td><span class="glyphicon glyphicon-thumbs-up"><%= link_to p.like, <link-of-like-path>, :remote => true, :id => 'likecount' %> </td>
<td><span class="glyphicon glyphicon-thumbs-down"><%= link_to p.dislike, <link-of-dislike-path>, :remote => true, :id => 'dislikecount' %></td>
ii. Now in controller you'll receive Ajax request & you need to give response in js format. So your like method will be like:
def like
@post.increment!(:like)
respond_to do |format|
format.html
format.js
end
end
def dislike
@post.increment!(:dislike)
respond_to do |format|
format.html
format.js
end
end
iii. create (action_name).js.erb file to handle js response. In your case it will be like.js.erb file in app/view/posts folder. Here write js code to replace like/dislike count.
$('#likecount').text(@post.like);
$('#dislikecount').text(@post.like);
If you want to go with your current code, then you need to add json handler in controller as
respond_to do |format|
format.html
format.json {@post.like}
end
and then use ajax success to replace text of like as,
jQuery(function($) {
$("likeAction").click(function(){
$.ajax({
url: path-to-like-function,
type: 'POST',
success: function(){
$('#linkcount').text(data);
}
error: function(error){
alert(error);
}
});
});
});
Upvotes: 1