I’m a total newbie when it comes to AJAX and need a little help. I have a posts_controller and a likes_controller:
A user can ‘like’ or ‘unlike’ a post. Right now, I’m trying to implement AJAX so that the like/unlike will toggle whenever a user ‘likes’ a post or ‘unlikes’ a post.
Before AJAX the page would refresh, and the code in the view would determine whether or not a given post was liked by the current user. I ran an if statement in the view, and depending on the results, displayed two different forms–if the post had not yet been liked there was a form to ‘like’ the post (create action), and if the post was already liked, there was a form to ‘unlike’ the post (destroy action).
Now that I’ve implemented the create part using AJAX, the like happens dynamically but the view does not change (I can see that the like is created via terminal / rails console, but the text on the link remains the same). I would like to know what is the best way to update the view without refreshing the page? I need to update the ‘like’ link and form with the ‘unlike’ link and form once the like happens via AJAX. Is the only way to do this via jquery?
here is my code:
likes_controller
class LikesController < ApplicationController
def create
@post = Project.find(params[:like][:likee_id])
respond_to do |format|
format.html{
current_profile.like!(@post)
redirect_to :back
}
format.js {
current_profile.like!(@post)
}
end
end
def destroy
@post = Like.find(params[:id]).likee
current_profile.unlike!(@post)
redirect_to :back
end
end
a snippet of the view:
%ul.dropdown-menu
%li
- if current_profile.like?(post)
= form_for current_profile.likes.find_by_likee_id(post), :html => { :method => :delete } do |f|
%a{:href => "javascript:void(0)", :onclick=>"$(this).closest('form').submit()"}
%i.icon-heart.icon-large{:style => "color: #fedc73;"}
Unlike this Post
- else
= form_for current_profile.likes.build(:likee_id => post.id), :remote => true do |f|
= f.hidden_field :likee_id
%a{:href => "javascript:void(0)", :onclick=>"$(this).closest('form').submit()"}
%i.icon-heart-empty.icon-large
Like this Post
create.js.haml file:
:plain
$(this).closest('form').submit()
Any help would be extremely appreciated. Thank you so much!
You could use
But instead of manually creating a link, you could generate one with rails:
This will work, even if js is disabled, adn you don’t need any form for this.
And of course this action should respond to .js and to .html. In the later one you can render the whole view, and in the .js you can insert a snippet of js which changes the link div into this refreshed one. Do you need any more explanation?