ficalino
ficalino

Reputation: 35

Why is my page not reloading view after posting a comment?

Learning ruby on rails while creating reddit clone, when I try to post comment my console returns that the comment is created but it's not reloading the page view and it returns an error saying

Uncaught TypeError: Cannot set property 'innerHTML' of null

at <anonymous>:3:52

at processResponse (rails-ujs.js:283)

at rails-ujs.js:196

at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.js:264)

create.js.erb:

document.getElementById("post-comments").innerHTML = "<%= escape_javascript(render partial: 'posts/comments', locals: {comments: @comments})%>"

comments_controller:

class CommentsController < ApplicationController

    def create
        @comment = Comment.new comment_params
        @comment.account_id = current_account.id
        
        respond_to do |format|
            format.js {
                if @comment.save 
                    @comments = Comment.where(post_id: @comment.post_id)
                    render "comments/create"

                else
                    # unable to save

                end
            }
        end
    end
    def comment_params
        params.require(:comment).permit(:message, :post_id)
    end

end

For more details, here is the git repo

Upvotes: 1

Views: 64

Answers (1)

Ninh Le
Ninh Le

Reputation: 1331

You have made a selector typo err, so change the comment/create.js.erb like this, this should work:

document.getElementById("post_comments").innerHTML = "<%= escape_javascript(render partial: 'posts/comments', locals: {comments: @comments})%>"
document.querySelector("#new_comment textarea").value = ""

The difference here is post_comments instead of post-comments

Upvotes: 3

Related Questions