简体   繁体   中英

rails ajax success not working

On Rails, I'm trying to create infinity like button which enable users to like multiple times, but Ajax seems not working. Here are my codes.

app/views/posts/_like.html.erb

<%= link_to 'B', post_like_path({:id => @post}), :class => 'like', :method => :post, :remote => true %>

app/controllers/posts_controller.rb

def like
  post = Post.find(params[:id])
  post.like += 1
  post.save
  if request.xhr?
    puts 'test' #'test' appears when like clicked
  else
    redirect_to :back
  end
end

app/assets/javascript/application.js

$(document).on('ajax:success', function(e) {
  console.log('test1') // 'test1' does not appear!!!
});
console.log('test2') // 'test2' does appear

Since you are getting your puts statement to show, it seems like you aren't too far away, but your like route needs to respond to your ajax request. In order to do that, I would set up a respond_to block inside your like method

def like
  post = Post.find(params[:id])
  post.like += 1
  post.save
  respond_to do |format|
    format.js
  end
end

With this, you would then create a js template, app/views/posts/like.js.erb

#like.js.erb
console.log('like clicked');

There's a couple issues that i see, your use of the path_helper you aren't instantiating @post as a variable (at least not from what you've shown), also your ajax method should probably look closer to this ...

#app/views/posts/_like.html.erb
<%= link_to 'B', post_like_path(:id => @post.id), :class => 'like', :method => :post, :remote => true %>    

#config/routes.rb
get "/some-path", to: "posts#index"
post "/some-path", to: "posts#like", as: "post_like"

#app/controllers/posts_controller.rb
def index
  @post = Post.find(params[:id])
end

def like
  post = Post.find(params[:id])
  post.like += 1
  post.save
end

#app/assets/javascript/application.js
$(".like").click(function(event) {
  event.preventDefault();
  url = $(this).attr('href');
  $.ajax({
    type: 'POST',
    url: url,
    success: console.log('success')
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM