From Rails JSON view to a JavaScript function

Currently, I am saving some JSON data in an active-record session and have set up a route and controller action to handle this. Everything renders perfectly fine in the browser, however, when I attempt to pass the route into a JavaScript function, the response that shows up in the browser network tab (specifically Chrome) is null.

Controller Code

class DataFilesController < ApplicationController
  def show
    render json: session[:my_data]
  end
end

Route Configuration

get 'data-file.json', to: 'data_files#show', as: :data_file

Javascript Function Implementation (inside view)

= content_for :javascript do
  :javascript
    accessibleAutocomplete({
      element: document.querySelector('#autocomplete-wrapper'),
      id: 'autocomplete',
      source: openregisterPickerEngine({
        url: "<%= data_file_path %>"
      }),
      templates: {
        inputValue: inputValueTemplate,
        suggestion: suggestionTemplate
      }
    });

Answer №1

The openregisterPickerEngine library utilizes the fetch Request object, which does not automatically include cookies in its requests. As a result, the session ID stored in the users' cookies is not passed to your DataFilesController endpoint, causing the session object to be null.

To resolve this issue, you must configure Request.credentials: https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

Unfortunately, the Request object is instantiated within the library code, making direct control difficult: https://github.com/alphagov/openregister-picker-engine/blob/master/src/index.js#L294

Your options are to either redesign the code so that the data endpoint no longer requires the session, or to fork or modify the library (or consider developing your own fetching and parsing mechanism).

Edit: It should be noted that the most recent version of the library uses xhr instead of fetch. Therefore, upgrading the library may resolve the cookie issue as, unlike fetch, xhr includes cookies by default in same-origin requests.

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 it possible to include tags in the response using Jquery.form AjaxSubmit?

After using ajaxSubmit on a form, the service sends back a number. Strangely, ajaxSubmit appears to be adding extra tags to the number. form.ajaxSubmit(function(data){ alert(data); }); Upon alerting the data, it displays: "<head></head>< ...

Arranging items based on parent and child relationships using Angular

In my angular project, I have a dataset that needs to be sorted in a specific way. 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: ...

Tips for displaying a div element alongside a button within a reactJS table

How can I position a div element next to a button in a ReactJS table? I have a table component where I want to display some options in a small window that closes when clicked outside. Options : https://i.sstatic.net/sT8Oi.png Action button in the table ...

Searching for array items by a list of values using JSON and JavaScript

My JSON array looks like this: [ { French: 'Hello', Spanish: 'Hello1', english:'Hello2' },{ French: 'Hello3', Spanish: 'Hello4', english:'Hello5 ...

A more efficient method for creating node.js functions to read and write files

Is there a more efficient way to optimize this code? var fs = require('fs'); var file = '/test.txt'; fs.readFile(file, 'utf8', function (err, txt) { if (err) return console.log(err); txt = txt + '\nApp ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...

How can we work with dates using mongoose?

Is it possible to set Date.now as a default value in a mongoose schema, or are all dates automatically converted to mongodb's standard format - ISOdate? What considerations should I keep in mind when storing dates? dates: { created: {type: Date ...

Spotlight barn doors in Three.js are an innovative feature that

I have been experimenting with three.js to build a scene featuring spotlights. Is there a way to achieve the barn door effect for the lights in three.js? I attempted using small cubes as barn doors to block the light, but it was not successful. I am look ...

Ways to utilize a React custom hook that returns a value within the useEffect hook?

I'm dealing with a custom hook that returns a value based on the parameters it receives. In order to update this value dynamically, I attempted to use useEffect but encountered issues as the hook cannot be called within it. How can I work around this ...

Are there any methods for identifying window overlap in a web browser?

I'm currently developing a web application that needs to perform a certain function when the user switches tabs. I've successfully detected tab switching and browser switching using: window.addEventListener('visibilitychange', () => ...

What is the best way to insert fresh input values into a different element?

click here to view image description I am working with an input element where I take input values and store them in an element. However, I would like to know how to input new values into the next element. Any assistance would be greatly appreciated. Thank ...

Node.js is throwing an error when attempting to delete a post using a hyperlink: "Cannot

Utilizing a hyperlink to remove a project from my main.ejs template is causing an issue when I click on the delete option. It shows an error message saying "Cannot GET /delete/6424f79c7dd4cd07ef49acae". Below is the code snippet for the delete hyperlink: ...

Iterating through form elements for validation using jQuery

Is there any way to accomplish this using jQuery? This is the initial setup: <input type='checkbox' class='sk1' /> <input type='text' class='skill1' /> <input type='checkbox' class=' ...

Javascript does not have the capability to parse JSON

Received a JSON response from a PHP file: [ { "color": "black", "product_name": "Prod2", "revision": "apps/" }, { "color": "green", "product_name": "Prod1", "revision": "dev/" } ] (successfu ...

Parsing JSON multiple times to extract data on the top 10 games from Twitch's API

Hey there! I have a little coding challenge for you. The current code below is only fetching the first channel from the JSON. My goal is to fetch all the streams and display them in a grid format with three streams per row. Can you help me achieve this? (B ...

Utilize the identical mathematical equation across various jQuery values

I have a JavaScript code that calculates the size of circles on the screen based on multiple variables. Currently, I am repeating the same equation for each circle by numbering all the variables accordingly. Is there a way to simplify this process and run ...

Exploring the process of displaying key names and values from JSON decoded data in Laravel Blade

I'm just starting out with Laravel I've created a form where users can input data, which is then saved as a JSON encoded string in the database. Here's the controller code: public function order_requirements(Request $request) { // ...

What are the different ways to utilize the $Scope variable in AngularJS without explicitly declaring it?

Could you elaborate on the functionality of the $Scope variable in AngularJS without needing to declare it in any specific place? ...

Create an HTML table with a line separating two table cells

I need help with creating a table row and td's dynamically using basic HTML and CSS. I would like to draw lines between the td's similar to the example image shown below. Can someone please assist me in achieving this? https://i.sstatic.net/GPd ...

Is it better to load AngularJS partials at the start instead of waiting until they are needed in Django?

In my Django project, I have a template folder where all the templates and partials for my app are stored. Instead of loading each partial individually based on controller requests in Angular, I want to preload all the partials into the template cache at t ...