Struggling to implement AJAX into a Rails application for updating comments, but encountering difficulties as the JavaScript file is not running in the

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... 

Answer №1

When you are in the create action and redirecting to a new page, it triggers a reload of the page. However, if you are making an AJAX call, you should render your js.erb file instead of redirecting.

def create
  @hairstyle = Hairstyle.find(params[:hairstyle_id])
  @comment = Comment.new(comment_params)
  @comment.hairstyle = @hairstyle
  @comment.user = @user

  if @comment.save!
    respond_to do |format|
      format.js # This will render the create.js.erb file for an AJAX call
      format.html do
        redirect_to hairstyle_path(@hairstyle) # Redirects to the correct path for an HTML call
      end
    end
  else
    render 'hairstyles/show'
  end
end

Answer №2

I finally resolved the issue at hand.

It turns out that I forgot to insert adjacentHTML after line 5 in my edited create.js.erb file code.

Below is the updated code snippet from my create.js.erb file, allowing users to post comments and have them appear below existing comments on the page. Additionally, the comment box now refreshes and clears after a new comment is posted:


  var newComment  = "<%= j render 'comments/show',comment: @comment%>";
  // 2. append the new review to the list
  var comments = document.getElementById('comments');
  comments.insertAdjacentHTML('beforeend', newComment)

  // 3. Empty out the input box
 var inputBox = document.getElementById('comment_content');
  inputBox.value = "";


Appreciate your assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Set the camera to view the world from a y-coordinate of 0 and descend

How can I make the top of the render area in Three.js point to y=0 in the world? I also want the camera to look straight (lookAt) These are my current values: camera = PerspectiveCamera camera.position.z = 1895.8448868133867 camera.fov = 20 screen.width ...

Having issues adding properties to a particular object within an array in JavaScript

In my JavaScript code, I am working with an object that represents a product. The object looks like this: { product_id: "2", product_name: "Drinks" } This object is named 'product'. There is an array that contains entries of the 'product& ...

Problem encountered when attempting to pass data from parent to child component

While using Vuu.js, I encountered an issue with passing a value from parent to child component. Initially, I had it working perfectly with a provided example. However, as soon as I tried changing the name, the functionality broke. I'm struggling to un ...

Set the value of this input element to its current value decreased by

I currently have several tabs with input fields on each tab. I have assigned the same class to each input field so that I can transfer values from one tab to another using the following code: $('.group_input1').change(function(){ $('.g ...

Instructions for running a script from a personalized NPM package

I have developed a unique NPM package that includes a script I want to run from another project. Here is an overview of my package: myScript.js console.log("The script has been executed!"); package.json { "name": "@myscope/my-script", "version": "0. ...

Adding static files to your HTML page with node.js

This is not a question about using express.static() In my application, I have multiple pages that share the same JS and CSS dependencies. Instead of adding <script> or <link> tags to every single page, I'm looking for a way to include the ...

Change the label of the "add to cart" button in WooCommerce once the item has been added to the cart

Is it possible to change the label of my add to cart button after it has been clicked and one item has been added to the cart, to say add one more to cart? I already have a Child-Theme with a second go to cart button that is functioning properly. However ...

Switch the appearance between two elements

In my HTML table, I have different levels of content - from main "contents" to nested "sub-contents" and even deeper "sub-sub-content". My goal is to hide all sub-content within the content cell that I click on. <table> <tr class=' ...

Creating Cascading Dropdowns in Rails 3

I am working with a table that has a self-referencing relationship: id | data | owner_id 1 | A | null 2 | B | 1 3 | C | 1 4 | D | 2 Therefore, B and C are related to A, and D is related to B. I would like to know how to create a dynamic ...

Modifying choices dynamically through Knockout imperative programming

I am using a knockout options binding which is structured like this: <select id="ddlProducts" data-bind="options: ShowProducts, optionsText: 'pruductskuname', optionsCaption: 'Choose a product...', value: currentproduct"></sel ...

Sending numerous data values, including arrays, via Ajax to PHP

Is it possible to pass multiple variables over to PHP using Jquery/Ajax? I am facing an issue where I can post multiple arrays if all variables are not arrays, but not if some of them are. Here is my code: <script> var mutype; var practiceArray = ...

Convert a string into HTML text using regular expressions

How can you correctly transform a string such as this: html attr = "value" attr2 = 'UnmatchInSubstrings' some \escapedTag content subtag subcontent /subtag br / /html into: <html attr = "value" attr2 = 'UnmatchInSubstrings'&g ...

Using AJAX to retrieve data from PHP consisting of two arrays and a string

When using AJAX to pass 2 arrays (each containing values from checkboxes) and a string (from a search textbox) to PHP, it's important to ensure the data is correctly formatted. The arrays selectedCategories and selectedCompanies are both arrays, whil ...

Retrieve elements within an element using its reference

<div ref={location} className={style.locations}> {locations.map(loc => ( <span onClick={onClick}> {loc.name} </span> ))} </div> My goal is to manipulate the <span> elements w ...

Events are documented as being removed when new content is introduced

In order to enhance user experience during long operations in my application, I am experimenting with adding a loading animation specifically on the login screen. To achieve this, I am utilizing code snippets that involve using IRazorViewEngine and ITempDa ...

ERROR: The specified module '../node-v11-darwin-x64/node_sqlite3.node' could not be located

Our server has a modified version of the Ghost blogging platform with updated content and design. I recently transferred the blog's app folder to my local machine and followed the provided instructions, which appeared to be straightforward. Quickstar ...

What is the process for displaying a PHP array in HTML5 audio and video players?

I am currently working with two PHP arrays. The first array, array "a," contains strings that represent paths for MP3 files on the server. The second array, array "b," contains strings representing paths for MP4 files. For example: $test = 'a.mp3&ap ...

Lost Vuex struggles when it is manually navigating a route in Vue-router

Exclusively on Safari browser, I encounter an issue when manually entering the URL in the navigation bar after logging in. For example, if I type "http://x.x.x.x:8080/gestione", the browser loses the vuex store state (specifically the gest_user module with ...

Display a loading screen when the page is reloaded

In my small Phonegap app, I currently have a button that triggers the page to refresh using this line of code: window.location.reload(); Although the page reloads quickly, there is a noticeable flash of elements being loaded at different times. To enhanc ...

What is the reason behind the NgForOf directive in Angular not supporting union types?

Within my component, I have defined a property array as follows: array: number[] | string[] = ['1', '2']; In the template, I am using ngFor to iterate over the elements of this array: <div *ngFor="let element of array"> ...