Chukwuma Kingsley
Chukwuma Kingsley

Reputation: 527

How to post a comment without refreshing the page.,

I want a user to be able to post a comment without the browser refreshing the whole page,

For now the comment gets submitted but the problem that I am facing is that, after a user submits a comment the page and whatever the user has put in the form remains there, I want it to get submitted properly and also the users input should clear out once the form has been successfully submitted.

my controller action

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(comment_params)


    @comment.user = current_user
    if @comment.save
        respond_to do |format|
            flash[:notice] = "Successfully created a comment"
            format.json { render json: @post }
        end
    else
        redirect_to :back
    end
end

My View

<div class="header-wrapper-blog">
  <div class="heading_for_blog">
    <div class="container">
      <%= simple_form_for([@post, @post.comments.build], remote: true, :html => {:multipart => true, id: "newcomment"  } ) do |f| %>
        <%= f.input :body, as: :text %>
        <button type="submit" class="btn btn-success" id="comment-form" name="submit"/>Submit</button>
      <% end %>
    </div>
  </div>
</div>

My current Ajax code

$(function(){
  $("#newcomment").on("submit", function(event){


  $.ajax({
      type: "POST",
      url: this.action,
      data: $(this).serialize(),
      success: function(response) {
        //update the DOM
      }
    });
    event.preventDefault();
  });
})

Upvotes: 1

Views: 647

Answers (1)

Ashutosh Tiwari
Ashutosh Tiwari

Reputation: 998

First of all if you are using remote: true, then no need to trigger another ajax event, which you are doing. So now you would have two cases, A.With remote: true B.With triggering Ajax.

Remove format.json { render json: @post } line from your controller and rails will render a file create.js.erb inside your respective controller views.In that file you can write logic to clear that form or update particular div. For Ex. $(#newcomment).reset(); and you can update a div also like $(#div).html("blah");

B.if you remove remote: true from your form then you can use ajax, which you have mentioned but in that case add dataType: script and it will render same create.js.erb.

C.If you dont want to follow above approaches then you can call this line $(#newcomment).reset(); in your success callback of ajax;

Upvotes: 0

Related Questions