The ActionController is encountering an UnknownFormat error when trying to respond to AJAX requests with js using

I've been scouring the internet for information on this topic, but I'm having trouble understanding how AJAX works with Rails. I've gone through the documentation multiple times and it's just not clicking for me.

From what I gather, AJAX is asynchronous and all you need to do to make a request in the view is add the code "remote: true". However, the part that's tripping me up is this line of code:

respond_to :js

It seems like it instructs the controller to respond to Javascript and you have to create a file for whatever JS action you want to perform. My project structure looks like this:

View

New.html.erb:

<p>Image Upload</p>

<%= simple_form_for @entries, remote: true do |f| %>   
  <% f.file_field 'input-image' %> 
<% end %> 
<div id="image-entry"></div>

View route:

views
   |
    -->admins
        |
         -->entries
                |-->new.html.erb
                |-->new.js.erb

Controller

entries_controller.rb

module Admins
  class EntriesController < ApplicationController
    before_action :authenticate_admin!

    def index
      render 'index'
    end

    def new
      @entries=''
      render 'new'
      respond_to :js
    end
  end
end

Controller route:

controllers
   |
    -->admins
        |
         -->entries_controller.erb

JS

new.js.erb

console.log('it works');

$('#input-image').click(function(){
  $('body').css('background-color', 'red');
});

JS route:

views
   |
    -->admins
        |
         -->entries
                |-->new.html.erb
                |-->new.js.erb

Error

The error message I encounter is as follows:

ActionController::UnknownFormat

So, I have some questions about this error and also regarding the correct naming convention for the JS file to ensure that respond_to functions correctly.

Answer №1

Response from Irfan Fadilah via Facebook:

The request you made is not being processed by the "new" method in EntriesController. Since the default form method is POST, Rails will be looking for the "create" method in your EntriesController.

To ensure that your AJAX request works properly, you should refer to the RESTful routing in the Rails Guide for more comprehensive information.

To make your AJAX request function correctly, add the "create" method in EntriesController and create a create.js.erb file (you can simply write alert("Hello"); or something similar to test it) in views/entries directory.

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

Struggling to render images within a child component in a React application when passed as a prop from the parent component

Currently immersed in a React project, here is the structured layout of my work: public index.html src App.js images facebook.png image.PNG linkedin.png profile.png twitter.png Profile Intro profileIntro.js data data.js Within App.js, I import ...

React is throwing an error because it cannot access the property 'length' of an undefined value

TypeError: Cannot read property 'length' of undefined When I try to run my React app, I keep getting this error message from the compiler. What steps should I take to resolve this issue? request = (start,end) => { if(this.state.teams.lengt ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

immutable chrome sqlite data objects

I have been utilizing a sqlite DB as the storage system for a web application. I have been directly using the objects returned from queries in my application. For instance: function get_book_by_id(id,successCallback,errorCallback) { function _successC ...

I'm having trouble mocking the image import correctly when trying to pass a test using jest with next.js. Why am I encountering this error?

Having some trouble passing a test with Jest in Next.js. The imported image doesn't seem to be mocked by Jest, and I can't figure out what's missing. Followed all the steps in the Next.js documentation. The fileMock.js is located at <rou ...

Automatically Populate list upon webpage initialization - React, Redux, Firebase

A webpage I am working on consists of two main components: Categories and Items By utilizing the function initCategories() called within the componentDidMount() lifecycle method of Categories, I successfully display all categories on the screen. The initC ...

Unable to activate primary error handler in my Node.js Express application

I have implemented node express (4.15.2) and used the default error handler provided by the express generator function to manage errors. Here is the code snippet: const app = express(); app.set('port', config.enviroment.portNumber); app.use(log ...

Instructions for obtaining and assigning a reference to a recently cached associated object within the Apollo client InMemoryCache

My data consists of a set of interconnected items like this: book { id ... related_entity { id ... } } Once Apollo caches it, there are two separate cache objects. The related_entity field on book points to an EntityNode object. Everything ...

JavaScript table supported by a REST API

Issue at hand: I am in search of a table component that seamlessly integrates with my web application. The challenge lies in connecting the existing REST endpoints to the table for data retrieval, whether it be paginated or not. Adjusting the endpoints t ...

The deployment of the Fire-base Cloud Function was successful and error-free. However, the function does not appear to exist in the Firebase system

After deploying a JavaScript Cloud Function, it shows that the deployment is completed. However, when I check Firebase, the function is not there. Oddly, TypeScript Cloud Functions deploy successfully. I followed all the steps outlined in the original Fir ...

Tips for uploading an Ajax-passed image as a Blob in MySQL with the help of Mysqli in PHP

I'm currently working on uploading an image using AJAX on the client side and PHP on the server side. The issue I'm encountering is that I can't seem to save the image as a blob in a MySQL database table using PHP. I'm struggling to def ...

Utilize JSON categories to assign groups to TextFields or Selects according to a JSON data attribute

I have retrieved multiple JSON groups from an API, each containing one or more questions objects. My goal is to display each question along with its corresponding response in a MUI TextField or Select component, based on the value of QuestionType. Current ...

AngularJS flexible route parameter

My AngularJS application has routes that can be either: www.website.com/blog/xyz www.website.com/blog/xyz/title/other-params In the second URL, the title parameter is used for readability purposes only and is not mandatory in the URL. Therefore, I have i ...

Switch up image transitions using Javascript

I have already completed the css and html structure for my project. However, I am encountering issues with the JavaScript functionality. I really like the image effect on this website: (the blue one). I have attempted to replicate it here: , but have bee ...

Dynamically including and deleting classes upon clicking using React

Looking for a solution to handle a list of links. The goal is to add a class called "is-active" when a link is clicked, while also removing any existing "is-active" classes from other links. Only one link should have the "is-active" class at a time. This ...

JavaScript code using the Jquery library to retrieve the following article from 'cached memory'

I am aware of the easier CSS options for my question, but I am determined to learn JS (Jquery), so please bear with me. My plan: Menu-items are connected to articles within my content division. Initially, only the first article (#intro) is displayed. All ...

What is the best way to format a date as "2020-01-16 07:29:43.657519000 Z" using JavaScript?

Upon discovering a format 2020-01-16 07:29:43.657519000 Z in a project, I am curious about the significance of the numbers 657519000 and how to replicate this precise format using JavaScript. When attempting new Date().toISOString(), I receive 2020-05-27T2 ...

Can someone guide me on how to personalize a marker icon in Quasar while utilizing Vue2-Leaflet for mapping?

I'm facing an issue with displaying an icon marker image in my Vue2-Leaflet and Quasar project. Instead of the desired image, I am seeing a broken image icon and encountering a 404 error in the console. Despite researching various solutions, I was abl ...

Discover the method for inserting a title attribute value into a span element

Utilizing AngularJS to retrieve and display data within a span element. I am now aiming to utilize this value as the title for another span element. The current code being used is shown below: <span style="display: inline-block; width: 160px">{{acti ...

What is the best way to reassign key-value pairs in JSON mapping using JavaScript/TypeScript?

Given {"a": {"name": "king", "firstname": "Thomas"},"b": {"age": "21"}} I'm exploring a simple way to convert it to {"name": "king","firstname": "Thomas","age": "21"} In the realm of Javascript/Angular. Any helpful suggestions are greatly appreci ...