user1573016
user1573016

Reputation: 51

How to get ajax comments working on Rails 4

I'm trying to get my comments to be saved with ajax so that the page does not reload. Here's what I've done so far, but it's not working.

How can I get this to work?

In my view file

<%= form_for [@book, inspiration, @comment], :html => { :class => "comment-form" } do |f| %>
 <%= f.text_field :content, placeholder: "Add a comment & hit enter.", :id => 'comment_submit' %>
<% end %>

Also in that file, I've include this:

<script>
 $(document).on('keypress', '#comment_submit', function(event) { 
  if ( event.which == 13 ) {
    event.preventDefault();
    var myData = $( "form" ).serialize();
          $.ajax({
              type: "POST",
              data: myData,
              url: <%= inspiration_comments_path(inspiration) %>,
              success: function(data){
            if(data){
                  alert('success')
            }  
          }        
    }); 
   }

  });
</script>

The comments are supposed to be submitted by pressing the enter key only. There's no button.

Another level of difficulty, these comments are about books. Those books are all shown on the page, and when you click on one book, it brings up a modal with information about it with the comments section. I tried giving the id selector a dynamic name, but that didn't change anything with the page load.

Thanks for your help.

Upvotes: 0

Views: 66

Answers (1)

Mohamad
Mohamad

Reputation: 35349

Rails has built in support for Ajax. You don't have to write your own jQuery to submit the comment. Use remote: true option with form_for and Rails will handle it for you. You will have to write a JavaScript handler, though, and make sure your controller responds in JavaScript.

For example:

<%= form_for [@book, inspiration, @comment], remote: true do |f| %>
# ...

Then, your controller would have something like this:

def create
  @comment = Comment.new(comment_params)
  @comment.save
  respond_to do |format|
    format.html # default without js
    format.js   # make sure you have a create.js.erb that will handle updating the dom
  end
end

Then you will want to create a comments/create.js.erb handler. This handler will have the necessary JavaScript to handle updating the dom, like inserting the comment, for example.

Check out the Rails Guides for more information.

Upvotes: 1

Related Questions