How can you handle a fetch request in JavaScript using js.erb?

I am attempting to send a post request to fetch all events (Jams) and dynamically update the page using AJAX. My controller is receiving parameters in JSON format, and I want to respond with JS similar to using remote: true on a link or button.

Currently working with Rails 6.0.2.2

Here is an excerpt from my .js file:

const getJams = () => {
  const mapCenter = map.getCenter();
  const mapBounds = map.getBounds();
  const token = document.getElementsByName("csrf-token")[0].content
  fetch(window.location.origin + "/search", {
    method: "POST",
    headers: {
      'Accept': "text/javascript",
      'Content-Type': "application/javascript",
      'X-CSRF-Token': token
    },
    body: JSON.stringify({
      map_center: mapCenter,
      max_lat: mapBounds._ne.lat,
      min_lat: mapBounds._sw.lat,
      max_lng: mapBounds._ne.lng,
      min_lng: mapBounds._sw.lng
    }),
    credentials: "same-origin"
  })
}

The method in the search controller where the data is processed looks like this:

def index
    @jams = policy_scope(Jam)

    respond_to do |f|
      f.json do |f|
        render json: {
          jams: render_to_string(
            partial: 'jams/jams',
            formats: :html,
            layout: false,
            locals: { jams: @jams }
          )
        }
      end
    end
  end

When executed, the server throws the following error:

Completed 406 Not Acceptable in 1ms (ActiveRecord: 0.0ms | Allocations: 889)

ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/searchs_controller.rb:7:in `index'

I'm trying to append elements inside my view within the search.js.erb file, where I have console.log("a");, but that JS doesn't seem to execute as nothing appears in the console.

If anyone can offer assistance, I would greatly appreciate it.

Below is the content of the jams/_jam.html.erb partial file:

<% jams.each do |jam| %>
<div class="jam-card">
  <%= image_tag jam.photo %>
  <%= jam.status %>
  <%= jam.user.first_name %>
  <%= jam.music_style.music_style %>
  <%= display_date(jam.start_date_time, jam.duration) %>
  <%= jam.participants.count %>/<%= jam.max_participants %>
</div>
<% end %>

Answer №1

Hint: Avoid using js.erb templates.

  • Using js.erb templates can disrupt the flow of your code. Switching between Ruby and JavaScript, server side and client side with every line of code can lead to messy and low-quality solutions.
  • js.erb templates are not optimized or served by assets pipes/webpacker, meaning they are not minified or delivered through a CDN.
  • Your well-structured RESTful server-side application will become cluttered with client-side logic and complex JavaScript views if you rely on js.erb templates for transformations.

Instead of using js.erb templates, consider responding to requests with JSON objects that the client side can handle for templating or return an HTML string in your JSON response to allow the real ajax handler to process it:

def index
  @jams = policy_scope(Jam)
  respond_to do |format|
    format.json do 
      render json: { 
        jams: render_to_string(
          partial: 'jams/jams', 
          formats: :html, 
          layout: false, 
          locals: { jams: @jams}
        )
     }
    end
  end
end

.then(function(response) {
  document.getElementById("some_element").innerHTML = response;
})

Some alternatives involve using request.xhr to send back HTML chunks in response to HTML ajax requests or utilizing custom content types, all of which are preferable to using js.erb.

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

Issues with CSS properties not functioning correctly within the class.col function

When attempting to apply specific CSS properties to a particular area (e.g., "Dashboard") by assigning the class name "main" to the div.col function in the HTML, I encountered an issue where the CSS property applied affected the entire page. The following ...

Is there a way to execute "npm run dev" within cPanel while I am currently working on a Laravel project?

Currently, I am working on a Laravel project and require to execute the following command in Cpanel terminal: npm run dev https://i.sstatic.net/bzxNj.png ...

transferring a delicious cookie to the browser

I have successfully integrated a basic login system using angular, express, and passport.js into an existing project by following the file structure and coding standards provided in angular-passport. Currently, users can sign up and log in without any iss ...

Set up AngularJS routing for accessing the Web API endpoint

I have encountered an issue with my AngularJS application and Asp.net Web Api. Both applications are hosted on port 80 of the IIS server. The problem arises when the web api URL cannot be accessed due to angularjs routing redirecting API calls to the root ...

Easily manipulate textboxes by dynamically adding or deleting them and then sending the data to a

Can you provide a simple example of how to dynamically add and remove textboxes and then display the results? I envision it like this: [Empty Textbox][Add button] When 'Value1' is entered into the textbox and 'add' is clicked, it s ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

A helpful guide on using workbox to effectively cache all URLs that follow the /page/id pattern, where id is a

Looking at this code snippet from my nodejs server: router.get('/page/:id', async function (req, res, next) { var id = req.params.id; if ( typeof req.params.id === "number"){id = parseInt(id);} res.render('page.ejs' , { vara:a , va ...

Looking for guidance on how to initiate or halt React Native Moti animation when the state changes? I've been running into issues where my method appears to disrupt

While experimenting with the Moti animation, everything was working perfectly until I included the playbackState === State.Playing condition. Unfortunately, once I added it, the animation looped only once and then stopped repeating. I'm puzzled as to ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

Preventing clicks within an iframe

Within an iframe, I have HTML content that includes hyperlinks. I need to prevent clicks on these hyperlinks. I managed to accomplish this using jQuery as shown below. However, I prefer not to use jQuery for this task. How can I achieve the same result ...

Exporting a React parent function to a child component

I have a React project where the rendering works fine, but I am facing an issue with calling a function declared in the parent component. Parent import React, { useState, useMemo, useRef, useCallback, useEffect } from "react"; import { AgGridRe ...

Making an ajax request with additional URL parameters

Is my thinking about this situation incorrect, or am I overlooking something? I've implemented a search box that performs wildcard searches in a database. This is done through an ajax request to avoid reloading the page and to display a loading icon ...

(React) Dynamically updating input fields based on calculations from other fields in real time

For days, I've been struggling with a perplexing issue where I have a simple form consisting of multiple divs, each containing four related inputs. My goal is to dynamically calculate the value of the last input in a div based on the values of the oth ...

Retrieving Data from a Promise - { AsyncStorage } React-Native

Currently, I am grappling with figuring out how to retrieve the outcome of a promise. My journey led me to delve into the React Native documentation on AsyncStorage available here: https://facebook.github.io/react-native/docs/asyncstorage I decided to uti ...

Free up Object Three.js

I've been working on a project that utilizes webGl and Three.js. The main issue I'm facing is related to memory deallocation. As the game progresses, a large number of objects are created, leading to excessive memory allocation. Despite trying v ...

A guide on resolving the TypeError 'download property of undefined' issue when using Puppeteer with browser.downloads.download

Using puppeteer, I am automating the login process to access my account on a content provider's site and download multiple zip files. After obtaining an array of links to download, I go through each link in a loop and utilize the browser.downloads.dow ...

Prevent users from uploading files when submitting the form

When I have a form with text and file inputs that submits an ajax request, I need to temporarily disable the inputs while sending the request. After the request is sent, I want to enable them again for another submit. Disabling text inputs is straightforw ...

Tips on transforming json data into a nested json data structure with data grouping?

Here is a sample of a json array: [{ id:1, topicid : 1, Topic:Topic_name, categoryid:1, category : category_name, subcategoryid:1, subcategory : subcategory_name, pageid: 1, pageurl : pageurl_name }] I am looking to convert the json dat ...

Making changes to two fields simultaneously

Is there a way for me to update the title of an article that is also duplicated in a field named "url" whenever the user enters text into the title field in real-time? Any advice on how I can achieve this? Thank you! ...

Determine various percentages through a single function

I am presented with a table of values displaying percentages for different elements in asteroids: astroid a nickel: 20% water: 25% cobalt: 55% astroid b nickel: 30% water: 35% cobalt: 45% astroid c nickel: 240% water: 45% cobalt: 65% To determi ...