Accessing instance variables from javascript can be made possible using the

I am currently facing an issue in my Rails app where I need scripts to have different behaviors based on the controller and action they originate from. To address this, I have set up the following code in my ApplicationController:

before_filter :save_action_controller  

def save_action_controller
  @action = action_name
  @controller = controller_name

Furthermore, in a javascript file filtered by erb, I have included the following snippet:

window.controller = <%= @controller || 'undefined' %>;
window.action = <%= @action || 'undefined' %>;

The issue I am encountering is that @controller and @action appear to be null within this context. Strangely, I can access them from views and helpers without any problems. Additionally, I am puzzled by how this doesn't trigger an exception when attempting to retrieve variables that don't exist.

What steps should I take to successfully access this data from javascript? Is there a recommended approach for achieving this?

Answer №1

This informative Rails Recipes tutorial covers methods for passing data to JavaScript.

While there are various approaches available, one particularly elegant method involves using data attributes (as demonstrated in the Rails Recipes tutorial). This can be defined in HTML like so:

<h1>Items</h1>

<div id="items" data-link="<%= items_link %>">
  Loading items...
</div>

and then accessed through JavaScript

jQuery ->
  alert $('#items').data('link')

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

Choosing a picture element based on the source attribute for identification

Currently, I am in the process of writing a script for a webpage and I find myself needing to update the icon associated with an image. The issue lies in the fact that the image only contains a tag structured like this: <img src="/pic1.png" alt="clear" ...

The Directive cannot be refreshed as a result of the ongoing "$digest already in progress" error

Within my controller, I have set a default value for a variable called "data". In my original project, I am using CouchCorner to retrieve data from a CouchDB and update the value of this variable. Inside a directive, I am watching the variable data and up ...

Landing page experiencing issues with client-side setTimeout functionality

Good Afternoon, I am currently working on implementing a loading animation for the pages on my website. However, I am facing an issue with the client-side setTimeout function not functioning as expected. Interestingly, the same function works perfectly on ...

Use the onClick attribute with Iframe

Is there a method to wrap an Iframe within another element to create a simulated onClick event? I am aware that Iframes do not support events, however, I require the ability to monitor clicks from my website that are being redirected through the Iframe. A ...

Implementing seamless redirection to the login page with Passport in Node.js

I have encountered a persistent issue while using node.js, express, and passport. After successfully validating the user with passport, my application keeps redirecting back to the login page instead of rendering the index page. Is there a problem with the ...

Prevent infinite scrolling from continuing once the end of the array is reached in React JS

My React app fetches the Flickr public feed, allowing users to scroll through endless content. However, I'm facing an issue where the app keeps trying to load more content even when it reaches the end of the list. This is evident from the loading mess ...

Notifying individuals of a file's unavailability using HTML tags

I recently created an API that is designed to deliver files to the frontend. Here is how it looks: <a href="downloadFile.aspx?file=token" download target="_blank"> The file download functionality is working fine. However, the issue arises when the ...

ExtJS variable not populating with servlet data

I'm facing an issue with my code where I am calling a servlet from JavaScript using an AJAX request. The data from the servlet is shown in a message box within the success function, but it's not being loaded into a variable called `myData` in Jav ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

The bluebird and mongoose collaboration utilizing the power of Promises

Currently, I am facing a challenge in a function that I am working on (I might be approaching it incorrectly). To provide some context, my goal is to add bulk data to a collection named "Sites" using a CSV format of site, country, type. I am attempting to ...

Recursive function: the process of storing numerous values in variables

There is a code snippet showcasing a recursive function designed to take a number, for example n=5, and produce an array counting down from n to 1 (i.e., [5,4,3,2,1]). The point of confusion arises just before the numbers/values of n are added to countArr ...

Issue with Material-UI AppBar buttons repositioning to center of screen upon page refresh

One of the components in my project is a Material-UI AppBar, which consists of various elements such as icons and buttons. Here is the code snippet for this component: import React from 'react' import AppBar from 'material-ui/AppBar' i ...

Error: The term "Image" is unrecognizable

I'm in the process of creating a website where I want to display images via links. If the image is missing or only 1 pixel wide, I need the site to show an alternative image. My technology stack includes Jade/Pug and JS. Before rendering the links on ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

"Troubleshooting issues with Material Design components in AngularJS: Why is <md-select> not functioning correctly

I'm attempting to implement the <md-select> tag, but I can't seem to achieve the same result as shown here. This is the code I've written: <div layout="column" layout-align="center center" style="margin: 0px 10px 0px 5px;"> & ...

RadRotator fails to resize properly when browser window is resized

I'm currently attempting to adjust the size of this control when the browser is resized. I searched through forums for a solution before posting my question. I came across a JavaScript function (unfortunately, it's not working). <script t ...

How come the useState hook is affecting a different state?

I have an array of data stored in the initial state as targets and another one as dataBaseTargets. My goal is to modify the value of targets without affecting the value of dataBaseTargets after a single useEffect call. However, I am facing an issue where c ...

Transform PHP array into a properly structured array or object that can be easily used in JavaScript

My PHP code contains an array that looks like this: $variation = [ attribute_label => "Choose your Color", attribute_name => "pa_choose-your-color", variations => [ "819" => "Red", "820" => "Blue", ...

Discover the locations where a mesh and a plane intersect using Three JS

After creating a three.js scene with a plane intersecting a mesh, I am trying to retrieve an array of points where the mesh's edge crosses the plane. Despite searching for solutions, I haven't found anything helpful so far. Please refer to the i ...

When the mobile navigation bar is tapped, it remains open instead of closing

The persistent challenge of the mobile navbar failing to close upon clicking an item continues to baffle. Numerous attempts from Stack Overflow and even tweaks recommended by ChatGPT have been futile in resolving this issue. Despite trying alternative me ...