When attempting to embed Ruby code within JavaScript, Ruby is not being acknowledged or

I am facing an issue with accessing values of a hash created by a ruby function inside javascript.

This is the code snippet from my controller:

class TransferController < ApplicationController
    def index
        require 'json'
        #@transfers = Transfer.select("transfer_id,section_id,sum(net) as net").group("transfer_id,section_id").having("sum(net) <> ?",0).order("transfer_id ASC")
        @transfers = Transfer.select("section_id,section_name,sum(net) as net").group("section_id,section_name").order("section_id ASC")

        h = Hash.new()
        a = []

        @transfers.each do |section| 
            h["name"] = section.section_name
            h["size"] = section.net
            a.insert(h)
        end

        @sectionhash = Hash.new()
        @sectionhash["name"] = "stringush"
        @sectionhash["children"] = a
    end
end

And here is the relevant part from my view:

<h1><%= @sectionhash["name"] %></h1>

<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var x = <%= @sectionhash["name"] %>;
alert(x);
</script>

While the HTML correctly shows the value from the hash, the embedded ruby code in javascript seems to be causing issues. I have tested with an alert message before the problematic line and it works fine. I have checked online forums and they confirm that my syntax is correct. Why could this be happening?

Answer №1

Remember to always follow the standard Javascript syntax rules.

var x = <%= @sectionhash["name"] %>;
will display: var x = stringush; but this is incorrect because there is no variable named stringush. Make sure to enclose the JS string in quotes like this:

var x = '<%= @sectionhash["name"] %>';

This code will show: var x = 'stringush'; which is the correct output.

Answer №2

It appears that you are seeking for the value of x to be the string "stringush". To achieve this, adjust your javascript as follows:

<script type="text/javascript>
    var x = '<%= @sectionhash["name"] %>';
    alert(x);
</script>

Make sure to include quotes in the script, otherwise, the javascript will interpret it as var x = stringush; which will result in x being undefined since no variable called stringush exists.

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 jQuery.each() failing to function properly in Firefox and Internet Explorer?

Having trouble with the $.each function behaving differently across browsers. I have lists with background images, and I want the parent div to fade in once these images finish loading. My code seems correct as there are no JavaScript errors in the conso ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

New to JSON: Why is my variable returning as undefined?

Embarking on my first JSON project has brought some challenges that I am struggling to overcome. Here's the task at hand. I have created a basic scraper using Apify.com to extract data from a specific website. The data is presented in JSON format, an ...

Retrieving values from a jQuery object array using keys rather than array indices

I am facing a challenge where I need to extract values from an object returned through $.post, but the order of the arrays can vary. Therefore, I must retrieve them based on their keys which are nested inside the array. An example is provided below. { Id: ...

You are limited to storing only up to 2 items in the localStorage

My goal is to save items in local storage as an array of objects. Initially, it works perfectly and stores the first element in local storage as needed. However, I am facing an issue where I cannot store more than one element. Below is the code block that ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

Using the match.params.id in React: A step-by-step guide

Having some trouble with my React code. I need to display the product name based on its ID, where the product data is fetched from product.js. I am using a router to switch between different products without reloading the page. import product from './ ...

Attempt to periodically load remote JSON data (error: Origin is not permitted by Access-Control-Allow-Origin)

My goal is to regularly load a .json file containing some information, and here is the code I have come up with: var updateIBEX35 = function () { var ibexText = document.getElementById("IBEX"); let url = 'https://www2.ecobolsa.com/js/data/i3 ...

The error message "Uncaught TypeError: Cannot read property 'createDocumentFragment' of null" occurs when using Jquery in Django

Struggling to identify the issue with this code that was previously functioning but started malfunctioning after reorganizing the JavaScript at the bottom of the page. It keeps throwing this error: https://i.sstatic.net/fozqo.jpg The line triggering the e ...

How can I add a Google Street View image to a document?

I attempted two different sets of code, but unfortunately, neither were successful. $("#search").click(function(){ var citySearch = $("#city").val(); var map = $("map"); var streetView = "https://maps.googleapis.com/maps/api/streetview?size=400x400&l ...

A guide on resetting a Nodemon server using code

At the beginning of server start, I have an array of JSON objects that are updated. But if I make changes to the JSON data using NodeJS FS instead of manually editing it, Nodemon does not restart. Is there a way to programmatically restart nodemon? ...

Why does xpath insist on choosing spaces instead of actual elements?

Here is a list of countries in XML format: <countries> <country> <code>CA</code> <name>Canada</name> </country> ... etc... </countries> I am looking to extract and loop through these nodes, so ...

Absence of event firing in .on method in Asp.NET Core 6 when using JQuery

I am currently working on an ASP.NET Core 6 application that utilizes JQuery. Here is the JQuery code snippet I have implemented in my page: @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

Error: Unable to access property 'addEventListener' of null. This issue appears to be related to a Chrome extension

It's been frustrating dealing with this persistent error. I'm in the process of creating my very first chrome extension and for some reason, I just can't seem to pinpoint what's wrong with this particular code snippet: let beginButton = ...

Initiate the month transition event within the fomantic calendar

In my project, I have integrated the fomantic calendar and it is working properly. However, I am facing an issue when it comes to changing the month. Is there a specific event for month changes in the fomantic calendar? I am struggling to make it work. Tha ...

Using Browserify to load the npm-module client-side for thepiratebay

I am currently facing an issue with my node.js server file. It successfully loads my site and runs JavaScript, but I encountered a problem when trying to include tpb = require('thepiratebay'); in the server.js file. Although it works fine in the ...

What is the most effective method for organizing an object by its values using multiple keys?

I'm interested in utilizing the sort method mentioned in the link but I am facing { "CYLINDER": 2986, "HYDRAULIC": 1421, "JACKS": 84, "INSTALLATION": 119, "REAR": 61, "JACK": 334, "TUBE": 1, "FEED": 114, "ASSEMBLY": 326, "DCS": 2 ...

Avoiding special characters in URLs

Is there a way to properly escape the & (ampersand) in a URL using jQuery? I have attempted the following methods: .replace("/&/g", "&amp;") .replace("/&/g", "%26") .replace("/&/g", "\&") Unfortunately, none of these are y ...

Having trouble sending an array from Flask to a JavaScript function

As a newcomer to web development and JavaScript, I'm struggling to pass an array from a Flask function into a JavaScript function. Here's what my JS function looks like: function up(deptcity) { console.log('hi'); $.aja ...