I want to update the number of likes on my "ideas" page when someone hit the like button using ajax
The button is displayed as follows in the ideas#show view ( the path currently directs to likes#create without ajax)
- unless signed_in? and current_user.likes? @idea
= link_to "Like this idea!", idea_likes_path(@idea), :class => "btn btn-large btn-block btn-success", method: :post, id: 'like_button'
- else
= link_to "Unlike this idea", idea_like_path(@idea, current_user.idea_like(@idea)), :class => "btn btn-large btn-block btn-inverse", method: :delete
My application.js has the follow:
jQuery.fn.ajaxFormSubmit = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
$(document).ready(function() {
$("#like_button").ajaxFormSubmit();
})
the LikesController#create method:
def create
like = Like.new
@idea.likes << like
current_user.likes << like
respond_to do |format|
format.html { redirect_to @idea }
format.js
end
end
and finally the create.js.erb:
$("#like_count").html("<%= pluralize(@ideas.likes.count, 'Like') %>");
With the above code, the button still refreshes the whole page. How do I make AJAX work?
You can submit an AJAX request without writing any Javascript by using the remote
option of the link_to
helper.
= link_to "Like this idea!", idea_likes_path(@idea), :class => "btn btn-large btn-block btn-success", method: :post, remote: true
This will send an AJAX request to the LikesController#create
action with the JS
format.
See: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
Have a try with UJS.
= link_to "Like this idea!", idea_likes_path(@idea), :class => "btn btn-large btn-block btn-success", method: :post, id: 'like_button', remote: true
Here remote:true
does the trick.
And then in your controller.
def create
@idea = Idea.where(id: params[:idea_id]).first
current_user.likes.create({idea_id: @idea.id})
respond_to do |format|
format.html { redirect_to @idea }
format.js
end
end