Transfer data from a Ruby JSON variable into a JavaScript variable

I've developed an index.html.erb file containing Ruby and HTML code, which is currently running on a webrick server at localhost without the use of Rails.

In my Ruby code, I have a Global JSON variable structured as follows :

@ruby_side_json = [{ :name => 'Will', :age => 23 },{ :name => 'John', :age => 30 }].to_json

I'm looking to assign this variable to a JavaScript variable located within a script.

My attempt using:

var javascript_side_json = <%= @ruby_side_json %>
has not proven successful. What steps should I take to achieve this?

Answer №1

When utilizing the rails tag within a script tag, remember to enclose it in single or double quotes.

To ensure proper functionality, modify your code as shown below:

var javascript_side_json = '<%= @rails_side_json %>';

Answer №2

To make the environment you're describing function properly, it seems like the best option would be to insert a <script> tag directly into the html code and ensure that it is rendered at the top, before any other javascript require tags.

Here's an example:

<head>
  <script>
    var data_from_rails = <%= @rails_data %>
  </script>
</head>

While this method may not be the most aesthetically pleasing, it should get the job done. If the script isn't placed before the JS require tags, the necessary data won't be available when executing JS code that relies on it.

Answer №3

In the scenario where Rails is not in use and JSON is successfully created through your to_json function, follow these steps:

<script>
  var jsonData = <%= @json %>;
</script>

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

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

Submitting the information through a for loop for every array within the nested array using Ajax

My data consists of a Sensor and multiple Alarms related to this Sensor. I am attempting to create several Alarms using a for loop, and then I want to use these Alarm variables in the Sensor JSON object. However, I am facing difficulties with this process. ...

Using JSON data with PHP, MySQL, and jQuery

I'm encountering an unusual issue. Whenever I try to access my JSON code with the corresponding numbers [0], [1], etc., I only get the first character of the object. Here's a snippet of my code: test2.php if(isset($_POST['getCustomersArr ...

Searching for a specific entry in home.db using user input is proving difficult when utilizing NEDB and Node.js. Passing parameters to index.js seems to be a challenge in

STUDENT NOTICE. I am currently studying Nodejs, express with NeDB and databases. My goal is to query my home.db (NeDB) for a specific record based on user input (in this case, a person's name). The overall process is illustrated in the following diagr ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

The functionality of Styles in Material UI seems to be malfunctioning

I'm currently learning how to use Material UI for React, specifically focusing on makeStyles. Below is the JavaScript code I have: import React from "react"; import MenuIcon from "@material-ui/icons/Menu"; import EventNoteIcon fr ...

Concentrate on Input in the Middle of the Text

Is it feasible to target a specific character within an input using JavaScript/jQuery for focus? Consider this input field: Would it be achievable to focus on the element and position the cursor after the first sentence, as an illustration? ...

Issue with React Router: Trying to access the 'history' property of an undefined object

I am developing a styleguide app that features two dropdown components. Users can select both a brand and a specific component, and the app will display the chosen component styled according to the selected brand. I aim to have these options reflected in t ...

Using JavaScript to skip duplicate rows in an HTML table based on group

My current task involves fetching multiple data from a database using AJAX and PHP. Once I retrieve the data successfully, I need to group the results in a specific format like the images shown below, including having a textarea field for each group. Here ...

Retrieving information from a database by employing AngularJS with the assistance of PHP

I am a beginner in using AngularJS and I am trying to retrieve data from a database using PHP. Here is the code I have tried: <html> <head> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2 ...

Modification of text within a text field via a context menu Chrome Extension

Currently, I am embarking on my first endeavor to create a Chrome extension. My goal is to develop a feature where users can select text within a text field on a website using their mouse and have the ability to modify it by clicking on a context menu. Be ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

What is the best way to send props to a CSS module in React?

Currently utilizing NextJS, I have a route named about that is displayed through page.js. Within /about/page.js, I am incorporating a component called <Hero /> and aiming to pass a prop to <Hero heroHeight={'height: 400px'} /> to my C ...

Error encountered while trying to render a Threejs FBX Object - undefined 404 (Resource not found)

I am facing an issue while loading a set of .fbx objects using FBXLoader on a WebXR App. window.fbxLoader.load("/assets/modelate_FBX/Vaza%208067134/Vaza 8067134.fbx", function( object ) { const flower = this.scene.children.find(c => c.name ...

Deconstruct the JSON object to extract values from both sides

When using volley to fetch API response, the data received is in the form of STATE_ID:STATE_NAME pairs (i.e. value:value pair). I need to extract and store both sides of the pair in separate Strings. These values are then intended to be placed in a spinner ...

The execution of my code differs between running it locally and in online code editors like CodePen or Plunker

Using jQuery Terminal, I have the following code: function display() { for (var i = 0; i < 100; ++i) { this.echo('line ' + i, { flush: false }); } this.flush(); setTimeout(function() { //thi ...

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

Node/ejs not recognizing Javascript files

I have been working on implementing a JavaScript code to create a hamburger menu when the screen is at a specific size, but unfortunately, nothing seems to happen. Here is how my directory structure looks like: public imgs javascript menu. ...

Jquery accordion remains open after clicking it

There are four accordions displayed on the page, with the open accordion only closing when another accordion is clicked. I would like the open accordion to also close when clicked. Below is the code I have implemented: $(document).ready(function() { v ...

Access the JavaScript array within a click function by dynamically generating the array name

Here's a scenario where I have an array like this: var first_array = ['foo','bar','foobar']; My goal is to run a click function that retrieves the array's name and iterates through its elements. The array has an ID ...