I am currently implementing AJAX in my Rails application to prevent the page from refreshing and scrolling back to the top whenever a new comment is added to an object. Instead, I want it to refresh and stay in the same position on the page.
To test whether the JavaScript I plan to write for this functionality is working correctly, I have console logged some text in a separate file called views/comments/create.js.erb
to confirm that the JavaScript is executing in my browser.
However, when I check the Console tab in my browser's inspector after creating a comment, I do not see the text that I console logged. Can someone please advise me on what might be causing this issue? Here is the link to my repository if needed: https://github.com/Angela-Inniss/hair-do
Thank you in advance for any help provided.
Comments Controller:
class CommentsController < ApplicationController
def new
@hairstyle = Hairstyle.find(params[:hairstyle_id])
@comment = Comment.new
end
# Rest of the controller code...
Views/Comments/Create.js.erb File (Expected Text in Browser Console):
console.log('hello ajax')
After confirming that the JavaScript is functioning properly through the console log mentioned above, I proceeded to update the create.js.erb file with the desired JavaScript behavior. However, the action I intended does not occur as expected. I aim to insert the user's comment at the end of existing comments without the page refreshing or moving to the top and then clear the comment box. If there are any discrepancies in the code below, could someone kindly point them out? My repository has been updated for clarity: https://github.com/Angela-Inniss/hair-do
<% if @comment.persisted? %>
// Code snippet for adding comment and clearing input box...