I’ve implemented a “like” button in ajax on my rails application, and I’m wondering why alert is not working.
In my controller,
def like
@post = Post.find(params[:id])
if current_user
if @like.empty?
@post.num_likes += 1
@post.save
else
alert = "You already liked the post :)"
end
end
end
and my like.js.erb file
$("#post_like_<%= @post.id %>").html("<%= @post.num_likes %>");
I initially wanted to redirect the user to the log in page if he’s not logged in, but I learned that it’s impossible to use redirect in a XML request. Could there be any workaround for me to request the user to log in when the user clicks the “like” button, while showing the alert message at the same time?
I thought including bootstrap popover in my js file as follow would be a workaround to using “alert” in my controller, but it didn’t work. I expected to see a popover under the number of likes.
$("#post_like_<%= @post.id %>").html("<%= @post.num_likes %>");
$("#post_like_<%= @post.id %>").popover('show')
Could anyone provide answers to my questions?
I appreciate your help!
To show a flash message triggered by an Ajax request, you can do something like this in your like.js.erb file (this presumes the presence of a division with the id “flash” on your page):
To redirect a user to the login page from an Ajax request can be done by changing the
window.location. Again in yourlike.js.erbfile:However, it might be sufficient to just display a flash message urging the user to log in with a link to the login path.