Ask A Question

Notifications

You’re not receiving notifications from this thread.

Trying to insert this without refreshing the page ~

JP asked in Rails

I am trying to insert a new comment on to the page without reloading using stimulus and javascript ~ I tried following along Chris in the nested comments video (NOTE: my comment is like his POST not comment) but I am having trouble~ I was wondering if anyone could help
It saves to the database but it isn't inserting. (It shows up if I reload the page )

Here are the codes

In the comments controller after being saved

   if @comment.save
      respond_to do |format|
        format.html { redirect_to course_unit_reading_passage_path(@course, @lesson), notice: 'Comment was 
            successfully created.' }
        format.js
      end

Since the above code is in the create
I've created create.js.erb
here is the code

var replies_form = document.querySelector("#comments")
replies_form.insertAdjacentHTML('afterbegin', '<%=j render partial: "lessons/comments/comment", locals: { comment: @comment }, format: :html %>')

var form_reply = replies_form.querySelector("form")

form_reply.reset()
form.classList.add("d-none")


And in the show page

      <div id="comments">   

          <%= render partial: 'lessons/comments/comment' %>
          <p></p>
      </div>

Here is the form for the comment

<%= form_with model: [@course, @lesson,  @comment], html: { class: local_assigns[:class], data: { target: local_assigns[:target]} } do |f| %>


  <div class ="form-group">
    <%= f.text_area :content, class: "form-control" %>
  </div>
  <div class="form-group">
    <%= f.submit :class => "btn btn-success" %>
  </div>
<% end %> 

NOTE: comments partial is in the comments folder nested inside courses
Any help would be greatly appreciated~
Thank you!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.