Passing JSON data from a Ruby controller to JavaScript in Rails 6.1 - Tips and Tricks

I am attempting to transfer JSON data from my database to the front-end in order to manipulate it using JavaScript. Initially, I created some temporary JSON data in my home.html.erb file like this:

<%= javascript_tag do %>
    window.testJSON_data = 
    [
        {
            "name" : "Bill Gates",
            "telephone" : 123456789
        },
        {
            "name" : "Elon Musk",
            "telephone" : 987654321
        }
    ];
    console.log(testJSON_data); /* Works as expected - will print JSON data in console! */
<% end %>

The code above successfully displays the correct data and JSON format in the console log. However, when I attempt to use my actual database data with a similar approach, issues arise. After passing the data to my home controller and trying to capture it in home.html.erb, the following Ruby code is executed:

class HomeController < ApplicationController
  def index
    @data = EmergencyFriend.all
    @jsonData = JSON.pretty_generate(@data.as_json)

    #render json: @jsonData
  end
end

I have experimented with various methods but have not been able to output the data as an object. My attempts include:

  • console.log(JSON.stringify('<%= j @jsonData.as_json.html_safe %>'));
  • console.log(JSON.stringify('<%= j @jsonData.as_json %>'));
  • console.log(JSON.stringify('<%= j @jsonData %>'));
<%= javascript_tag do %>
    console.log('<%= j @jsonData %>');
<% end %>

WILL RETURN:

[
  {
    &quot;id&quot;: 1,
    &quot;first_name&quot;: &quot;Emergency Contact&quot;,
    ...
    &quot;dial_code&quot;: 357
  },
  {
    ...
  },
  {
    ...
  }
]

After spending quite some time troubleshooting, I'm still unable to identify where the issue lies. Whether it's incorrect data transfer or misprinting of the data remains unclear to me.

What steps should I take to effectively store JSON data from a Ruby controller to JavaScript?

Answer №1

Apply the html_safe or raw method to render that string safely.

<%= @jsonData.to_s.html_safe %>

Another option is to retrieve it through an ajax request.

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

What is the best way to extract data from a JSON response?

Looking to parse a JSON response with a JSON array nested inside another JSON array. Any tips on how to efficiently parse it? Hoping for the best example of multiple JSON array parsing. All fields are dynamic so need this kind of response from developers ...

Exploring the power of QueryTask in ArcGIS JS API 3 for running multiple queries

When using QueryTask in ArcGIS JS Api 3, I encountered a challenge where I needed to execute multiple queries in one call. After referencing the documentation, I realized that this functionality was not directly supported. This is my current implementatio ...

display angular filter for mat radio option selected from mat-radio group

On the screenshot provided below, there are 2 buttons within a mat radio group. The condition is that if modelForm.get('schedule').value equals '1', then only display the radio button with the value 'A'. Otherwise, show all va ...

Is there a way to verify if the email entered into the input field is included in the list provided below?

Whenever an email is entered into the text box, a validation message should appear next to the input field. The inputted email should be checked against the list of emails below, and if it exists, an error message needs to be displayed. I need assistance w ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...

A walkthrough on reading JSON strings containing arrays using PHP

When making a PHP POST request, I am sending a JSON string that looks like this: {"mobile":"0000000000","otp":"970996", "items":[{"pid":"12", "vid":"20"},{"pid":"13", "vid":"2"}]} On the server side, I need to extract the mobile number, OTP, pid, and vid ...

"Utilizing Bootstrap's dropdown.js script independently: A Step-by-Step Guide

Has anyone been able to successfully use the Bootstrap dropdown.js component without integrating the entire Bootstrap library? I've attempted it, but haven't had any luck so far. Upon reading the documentation, it appears that the dropdown.js co ...

Error: Mongoose Schema Undefined when Route is Added in Separate File

For the sake of organizing my code, I made the decision to separate all of my schemas and routes into different files within my directory, and then required them in my app.js. Each schema corresponds with each route. This method has worked for all but one ...

3D Object Anchored in Environment - Three.js

In my current scene, I have two objects at play. Utilizing the LeapTrackballControls library for camera movement creates a dynamic where one object appears to rotate based on hand movements. However, an issue arises as the second object also moves along w ...

Solving the checkbox toggle challenge with recursive functions | Recursive checkbox challenge

I'm currently working on creating a checkbox tree with the following data structure for items const checkboxes = [{ field: 'ARTICLE', id: 41, name: 'Article', parentId: null, checked: false, children: [ ...

Creating a simulated class within a function utilizing Jest

Currently, I am in the process of testing a controller that utilizes a class which functions like a Model. const getAllProductInfo = (request, response) => { const productInformation = new ProductModel().getAll(); response.status(200) resp ...

Issues with the Textarea StartsWith Function Being Unresponsive

Attempting to use the startsWith function on a textarea, but it seems like there may be an error in my code. Since I am not well-versed in Javascript, please forgive any obvious mistakes. I did try to implement what made sense to me... View the Fiddle here ...

Utilizing Mathematical Calculations Across Multiple JavaScript Functions

Just dipping my toes into the Javascript realm and attempting to crack this task my instructor assigned. Here's what he expects from us: Create a function to kickstart the program. Name it start() Inside the start() function, invoke a function n ...

Automatically load file and play audio when the page is loaded

I have created code that allows me to input an mp3 file, output the audio, and display a visual representation of the music. Currently, loading the file is done manually through an input type="file". Now, I want to change it so that the music automaticall ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Are you experiencing issues with the map displaying inaccurate latitude and longitude when clicking on a specific point?

I've successfully created a simple polyline on Google Maps and attached a click event listener to it. However, I'm encountering an issue where clicking on the line provides me with latitude and longitude coordinates that point to Canada, even th ...

Error: Unable to perform 'getComputedStyle' on the 'Window' object: the first parameter must be of type 'Element'

My goal is to create a rotating effect with a center circle containing 5 inner divs. When the device is rotated on the gamma axis, I want the circle div to rotate in accordance with the gamma degree, while the inner divs rotate in the opposite direction to ...

Combining the results of JavaScript comparisons into a unified object array and adding a new value if it matches an existing value within the same

I am interested in consolidating the array to represent the base folder hierarchy. In the array provided, "Level 1" is the lowest level with no children folders. The "other level" contains various folders all under the "Top Level." The array structure is ...

Converting a JSON array into a list of strings in a Spring application using the GSON library

Here is the JSON data I have: ["2848","241"] Using the jQuery code below, I am building a list from selected checkboxes: var list = []; $.each($("input[class='selected']:checked"), function(){ list.push($(this).val()); }); The ...

Using AngularJS to Extract JSON Data from a Table in an HTML Document

In the context of angularjs: I have a table with 2 fixed columns (ID & Comment) and additional columns that are added dynamically by the user clicking a button. The user can input data into the rows of this table, and I need to extract/ read this data. H ...