Enhance your Rails form calculator by integrating AJAX without the need for a database

I am currently in the process of integrating Ajax into a non-database form calculator in Rails. However, I am encountering an issue where it does not seem to be responding and is giving me a 204 no content server answer. I have been trying to troubleshoot this problem on my own, but I find myself stuck. Since my knowledge of JavaScript is quite basic, a detailed response would be greatly appreciated. The calculator works perfectly fine without Ajax and passes all tests.

Calculator Controller

class InterestCalculatorController
  def new        
    respond_to do |format|
      format.html { render 'index.html.erb' }
      format.js 
    end 

    # If accepted parameter is integer, then it shows in view as 5, when it
    # is float, it shows as 5.1  
    @first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
    @second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i

    # How many percent is number from the number 
    number_to_number(@first_0, @second_0) 

 private 

   def number_to_number(a = 0, b = 0)   
    # If the first number is zero, it sends 0% answer. If the second number is zero 
    # and the first number is nonzero, it sends infinity. Otherwise simple formula calculation.
    if a.zero?
      @result_0 = 0
    elsif b.zero?
      @result_0 = "infinity"
    else
      @result_0 = a.to_f / b.to_f * 100
    end  
  end
end

index.js.erb

document.getElementById("answer_0").innerHTML = <%= @result_0 %>

View index.html.erb

<h1>Interest Calculator</h1>

<div id="interest_calculator_main">
  <div id="interest_calculator">
    <%= form_for :interest_calculator, url: { action: :new }, method: :get, remote: true do |f|   %>
      <p>How much % is one number from another?</p>
      <%= number_field_tag :a_0, params[:a_0], step: :any, id: "first_number_0" %>
      <p>of the number</p>
      <%= number_field_tag :b_0, params[:b_0], step: :any, id: "second_number_0" %>
      <%= f.submit 'Calculate!', id: "number_to_number" %>
    <% end %>

    <% unless @result_0.nil? %>
      <p>Number <%= @first_0 %> from number <%= @second_0 %> = <label id="answer_0">%</label></p>
    <% end %>
  </div>
</div>

Answer №1

Your form is being submitted to the latest action, however, you do not have a corresponding template for that action (e.g., new.js.erb). As a result, you are receiving a 204 No Content response, which will be displayed in your server logs as follows:

No template was found for InterestCalculatorController#new

To resolve this issue, simply rename index.js.erb to new.js.erb, and the error message will no longer appear.


In addition (unrelated to the previous error), it is recommended to update <%= @result_0 %> to "<%= @result_0 %>" within your existing new.js.erb file:

document.getElementById("answer_0").innerHTML = "<%= @result_0 %>"

Failure to make this change may result in another error being triggered if @result_0 is assigned a value of "infinity".

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

Show the user's username on their profile page by retrieving the name from the database

Upon successful login/signup with various services, I want to display the username on the profile page. However, my database stores user data in different fields depending on the service used - user.twitter.name for Twitter logins, user.google.name for Goo ...

Can you make two elements match each other at random?

Currently, I am working on developing a word guessing game where the displayed image should correspond with the word to be guessed. Unfortunately, I am encountering two major challenges in this process. Firstly, I am unable to get the image to display co ...

Encountering issues when attempting to invoke a function from an external file in Angular4

When attempting to call a method from an external file using Angular4, I am encountering the following error: Error: ERROR in src/app/about/about.component.ts(22,9): error TS2304: Cannot find name 'checkJS'. Below is the code I am working with ...

JavaScript's innerHTML property is failing to update

Hello there, I am currently attempting to update the innerHTML content of the script below: <div id="global-alert-queue" class="layout-wrapper"> <div class="alert success animate-in" role="alert"> Your submission was successful. <button i ...

How can I retrieve a formController in AngularJS?

When trying to reset the data in a form and calling form.setPristine(), I encounter an issue where the formController is not registered within the $scope. It may sound like a basic question, but how can I locate the formController? Within the code snippe ...

Choosing various choices using AngularJS

My goal seems simple using vanilla JS, but with AngularJS, I'm looking for the best way to achieve it within the framework. I aim to update the selected options in a multiple select box without adding or removing any options. Below is a snippet of my ...

Disabling the authentication prompt in the browser

Apologies for the repetition, but I would like to pose a more general question. Is there any method on the client side of a web application to predict if requesting a resource will result in a 401 status code and trigger an unattractive authentication pro ...

Exploring the Power of Promise Chaining: Understanding the Distinction between .animate and setTimeout

I am seeking clarification on how promises work in JavaScript. I am struggling to understand the difference between executing a chain composed of jQuery.animate and setTimeout. For example, if I write the code below: var promise = new Promise(function(re ...

Reverse changes made to a massive object and then redo them

My current project requires the implementation of undo-redo functionality for a product. At the moment, I am managing a substantial Object retrieved from a MongoDB collection The structure is as follows: { cart:{ products:[ { name: " ...

JavaScript shows undefined fields for results from Mongoose/MongoDB

Why is the item logging as an object with a parameter, but when trying to access that parameter it's undefined? My attempts so far: console.log(item) => { title: "foo", content: "bar" }, which is fine console.log(typeof item) => object consol ...

Tips for optimizing the speed of uploading multiple images/files from a client's browser to a server using JavaScript

We are seeking ways to enhance the file upload process in our application, particularly for managing large files. Any suggestions on accelerating this process would be greatly appreciated. ...

Using Regex in JavaScript to split a string based on a saved pattern

I have a specific sentence to work with: var sentence="example of+a+string"; My goal is to split the string by the + symbol only when it occurs after the word "of". When attempting this with the code: sentence.split(/of(\+)/) The result splits th ...

When AJAX is used, no request body is being consumed

I am facing an issue with AJAX when calling a REST API post method. I am using NodeJS to build the API side and the script appears as follows: const route = express.Router(); route.post('/tambahproduk',async(req,res)=>{ console.log("API ...

steps for setting up babel-cli and babel-preset-react

I attempted various methods of installing babel-cli babel-preset-react Here's what I tried: npm install --save-dev babel-cli babel-preset-react However, when I run babel -h An error message appears saying The program 'babel' can be found ...

Ways to retrieve JSON data using Angular JS

I'm currently working on populating my table with data. The URL returns JSON data, but I'm struggling with how to retrieve it using AngularJS. Here is my services.js: angular.module('OrganisatieApp.services', []) .factory('organi ...

Twice the clicking actions triggered by the event

Whenever I try to trigger a function by clicking on the label text, the click event seems to be firing twice. HTML <label class="label_one"> Label One <input type="checkbox"/> </label> However, if I modify the HTML code as f ...

Using Vue to download a file by linking to the href and incorporating a Vuetify v-btn

Having recently started learning Vue.js, I am currently encountering difficulty with a seemingly simple task. My goal is to add a Vuetify button to my webpage that allows users to download a file. However, I am struggling with getting the href attribute t ...

Tips on modifying classes within specific sections of HTML tables

I attempted to create calendar-like tables, In my script, I am trying to handle events being registered. My goal is to change the classes of cells from 2 to 5 when they are clicked on, and change the cell colors from first to hovered to aqua. For this p ...

Implementing functionality: Removing a row and applying a CSS class upon button click

Check out the fiddle below: https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/ I need help with creating a remove function and adding a CSS class to a clicked row. 1. When I click on "remove", the clicked row should be deleted. When I click on a row, ...

Using JavaScript to show a prompt message inside an h1 tag within a newly created div

I have developed a basic JavaScript program that opens a prompt dialog when the div tag is clicked, allowing the user to enter text. The program then creates a new div element and displays the entered text above it. However, I am facing an issue where I wa ...