Facing an issue with the format.js not functioning properly in Rails version 6.1.3

styles.css

@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap");
body {
    font-family: 'Roboto', sans-serif;
    color: #333;
}

.wrapper {
    max-width: 960px;
    margin: 0 auto;
}

button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
}

about_conttroller.rb

class AboutController < ApplicationController

  def index
    @info = Info.new
  end

  def create
    @info = Info.new(info_params)

     respond_to do |format|
  
     if @info.save
       InfoMailer.with(info: @info).notification.deliver_now
        format.html {redirect_to about_path}
        format.js { alert('Info saved successfully!') }
    
     else 
      format.html {render :index}
      format.json {render json: @info.errors, status: :unprocessable_entity}
    end
  end
end

private ##

 def info_params
   params.require(:info).permit(:title, :content)
 end
end

trying to test the alert message after saving info in the database.

alert.js.erb

alert('Alert message displayed!');

home.html.haml

.main_info_inner 
  = form_for @info , url: info_path do |f|
    - if @info.errors.any?
      %ul 
        - @info.errors.full_messages.each do |msg|
          %li= msg 
    #infoForm.row.info_form
      .form-group.col-md-6
        = f.text_field :title, class: 'form-control', placeholder: 'Title' 
      .form-group.col-md-6
        = f.text_area :content, class: 'form-control', placeholder: 'Content'
      .form-group.col-md-12
        %button.btn.submit_btn.blue.form-control{:type => "submit", :value => "submit"} Save

No console log is shown after submitting the form.

If you have any ideas on how to troubleshoot format.js not executing properly or alternative ways to create alerts without using controllers, your assistance would be greatly appreciated.

Answer №1

It appears that adding remote: true is necessary in this case

= form_for @contact , url: contacts_path, remote: true do |f|

According to the documentation:

:remote - if set to true, will allow Unobtrusive Javascript drivers to control the submit behavior

Enabling this option adds the js header to the request, allowing the rails controller to respond with the js format.

Answer №2

Check out this resource from Learn Ruby on Rails

<%= form_with(model: @article, id: "new-article", remote: true) do |form| %>
  
<% end %>

Remember to include remote: true

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

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

Creating three-dimensional text in Three.js

My script is based on this documentation and this resource. Here is an excerpt of my code: <script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script> <script> var text = "my text", height = 20 ...

Does the react key have scope limited to the local environment or does it have

After reading this intriguing article discussing the use of the index as a react key, I began to ponder. Imagine having two distinct lists: <List1> <el key="1" /> <el key="2" /> </List1> <List2> <other-el key="1" / ...

Strategies for resolving Timeout issues in REST API

One of the challenges I'm facing involves a stored procedure that takes 10 seconds to execute and returns 10,000 records of data. Despite this, whenever I call the API, the connection times out. Increasing the REST request timeout seems like it could ...

Clicking on an iframe activates the loading of the displayed page

I'm attempting to create a functionality where clicking on an iframe will load the page it is displaying. I experimented with placing it within an tag, but that didn't produce the desired result. The effect I'm aiming for is similar to zoom ...

Error in Jquery validation caused by incorrect file extension type

Within my HTML form, I have multiple inputs set up for validation purposes: <form role="form" id="addForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="userName">U ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

Adjusting the height of a container dynamically in React while flex items wrap using CSS

In my React project, I have a container called "answers-container" with multiple buttons inside it, laid out using flexbox with flex-wrap: wrap to allow them to wrap onto the next line when the container width is exceeded. However, I'm facing an issu ...

Using Jquery Datatables to populate with an asp.net webmethod through ajax calls

When it comes to using ajax with a webmethod to populate something or a table, I usually don't have any issues. However, I've been struggling to find a way to incorporate the jQuery datatables plug-in into my workflow. $.ajax({ type: "POST", ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...

Is there a way to slow down the falling effect on my navigation bar?

As I was working on my personal website, I had a creative idea to add a falling-down animated effect instead of keeping the layout fixed. Utilizing bootstrap for navigation, I encountered some difficulty in controlling the speed of the falling effect. Any ...

Database-driven Ajax autocomplete feature populates search field

While searching for solutions on creating an autocomplete search box, I noticed most discussions focus on returning Json from the controller action. However, my issue lies in the fact that my controller action passes actual json data as a page instead of e ...

Permission not granted on Internet Explorer versions 10 and 11 for ajax requests targeting localhost

I have been facing an issue with making an ajax call from a server on the internet to my localhost. This works perfectly fine on browsers like Firefox and Chrome, but I am encountering problems specifically with Internet Explorer versions 11 and 10. The r ...

What is the best way to increase a specific value in an array of objects once it has been located (using findOne()), but before it is

I'm looking for a more efficient way to update an object within an array of schemas in one database request instead of two. Currently, I use findOneAndUpdate() to increment the field if the object already exists, and then I have to use update() if the ...

If the data remains the same during each setInterval, no action is taken. However, if the data changes

After my DIV is loaded with data from a $.get request on doc ready, I set up a setInterval function to run every 5 seconds. My goal is to compare the new data fetched by $.get when setInterval runs, and only update the #are_friends element if the data has ...

Scroll horizontally through the number field in Chrome

I have configured a number input field with the text aligned to the right. Scenario: While testing, I discovered that selecting the entire text or using the middle mouse button to scroll within the input field allows for a slight leftward scrolling of ab ...

What is the best way to recycle Vue and Vuetify code?

<script> export default { data () { return { my_alert: false, text: '', color: 'success' } }, methods: { openAlt (text, color) { this.text = text this.color = color this.my_ale ...

Issue with Selenium webdriver functionality in Electron development build

I've been working on an Electron project where I render an HTML page with a button that, when clicked, triggers a Node.js script (via IPC) using Selenium to scrape webpages. Here is the structure of my project: -app/ --index.html --ma ...

Error: The script is unable to access the property "div" because it is undefined

I keep encountering this issue "Cannot read property 'div' of undefined" This is the snippet in question function validateData(){ for(let j = 0; j < 13; j++){ if(dataArr[j].data.textContent === resultSet[j].result.div. ...

Detecting browser reload in React/Typescript: A guide

Is there a way to determine if the browser has been reloaded? I've explored various solutions, but most suggest using code like this: const typeOfNavigation = (performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming).type ...