Exploring the dynamic JSON object from D3 in a Rails view

Currently, I am in the process of learning D3 and my initial attempt involves showcasing a graph where I manually hard-code the json data.

To demonstrate this, I have put together a JSFiddle which you can view here: http://jsfiddle.net/Nu95q/1/

The JSFiddle successfully showcases the graph as intended.

My next goal is to incorporate this into my Rails project by passing the json data using an ajax link. Upon clicking the link, I aim to generate the json data in the controller and then swap out the graph with the new one.

The D3 code resides in

assets/javascripts/my_controller.js.coffee

This snippet illustrates what I have in my controller:


def identification_item
  @sii = params[:sii_id]
  @fragments = SpectrumIdentificationItem.find(@sii).fragments
  respond_to do |format|
    format.js { render json: @fragments }
  end
end

Upon inspecting Chrome's Network panel, it confirms that a json object is generated with the accurate data.

At this point, my query is on how I can access this json variable in D3. I have attempted to replace the hardcoded variable with the json generated in the controller like so:


jsonFragmentIons = @fragments

However, it appears that @fragments is inaccessible in

assets/javascripts/my_controller.js.coffee

(I have explored SO for information on "accessing json in D3," yet the questions I've looked at mainly pertain to reading a .json file or utilizing a static variable containing the json rather than a dynamic json object)

Furthermore, it is possible that I may be missing fundamental concepts regarding how json data is exchanged between the client and server sides due to being relatively new to this field. Therefore, any guidance provided would be greatly appreciated.

Answer №1

If you're encountering a similar issue, here's how I managed to resolve it. It turns out that using d3.json is necessary. Referencing the d3 documentation, it states that d3.json is used for "loading data asynchronously" and any code relying on the loaded data should be within the callback function.

In my Coffeescript file, I implemented the following:
d3.json "json_generator_controller/action", (error, json) ->
 return console.warn(error)  if error
 data = json
 visualizeD3spectrum(data)

Following this,

visualizeD3spectrum = (data) ->
 //D3 svg operations go here

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

Can you explain the purpose of 'cb' in the multer module

Within the code snippet below, taken from the multer API, both the destination and filename options consist of anonymous functions. These functions contain an argument named cb. I am curious whether these callback functions are defined within the multer ...

Delaying http requests until cache is fully prepared without the need for constant checking

In a unique scenario I am facing, my http requests are caching intermediary results on the server. If the cache is not found, then another server is requested to build it. These requests are sent consecutively (in a loop) using AJAX to a Node Server, with ...

In an AngularJS application, when using fullPage.js on the homepage, it is recommended to ensure that it is

Within my angularJs application, I have implemented fullPage.js on the homepage exclusively to ensure no interference with other pages or routes. To make this possible, I am currently triggering a destroy action during the locationChangeSuccess event. I a ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

The error message "MongoDB - MongoError: connect ECONNREFUSED" indicates a

I am encountering an error every time I attempt to connect to mongoDB. Despite looking through various similar questions, I have yet to find a solution for my specific issue. Here is the exact error message: connection error: { MongoError: connect ECONNR ...

Move tables by dragging and dropping them into place

Currently, I am on the lookout for a drag and drop plugin that works with jQuery, Angular, or JavaScript to help me create dynamic tables. Specifically, I need a plugin that allows me to add new tables through drag and drop functionality. While I have com ...

navigating directly to a particular slide within a Bootstrap carousel on a different page by clicking

Attempting to set up a bootstrap build, where clicking on certain states on one page will direct the user to a specific slide on another page. I'm struggling to grasp this concept. A friend of mine, who is a Javascript developer, provided some code f ...

The Google Map is not showing all the details

Our app is developed using ReactJS on Rails API, with a Google map integrated. However, when visiting this link and clicking "Map View", some grey space appears under the Google Map. An example image can be found here: example We are having trouble findi ...

Working with AngularJS $resource: including an array element in paramDefaults

I'm currently working with the twitch.tv API and utilizing the Angular $resource factory. My goal is to access the endpoint: GET /channels/:channel. What I want to achieve is to retrieve the channel for each element within an array. I attempted using ...

What does Angular classify as a watcher?

What qualifies as "watchers" within Angular? Are watchers the only type of monitoring mechanism, or do other Angular elements like ngModel also serve as watchers? Am I overlooking something crucial? For example, do watchers play a role in enabling directi ...

Repeating declarations in AngularJs controllers when injecting services

Currently, my controllers are set up using array injection. However, as I pass more services to the controller, I end up repeating each one twice - in the array and as a parameter. I came across a helpful discussion on Injecting a service into another ser ...

The window fails to load properly after building, but functions perfectly while in development server mode

My application is not displaying a window after it's built, but it works perfectly fine when I execute npm run serve Even though there is a process running in the task manager, the same issue persists if I try using the installer. I'm not receiv ...

Retrieve the binary data of a Bitmap from Redis

Currently, I am working on developing a user activity feature that involves tracking the daily activity of each user. My idea is to use a bitmap where active users are assigned a value of 1 for each day. SETBIT users:2015:9:30 <userid> 1 Instead of ...

Is there a way to transform a stringified array into an array in JavaScript if I do not have access to the original string?

Recently, I encountered a challenge where I had an array of items enclosed within "", and not '' (if that distinction matters): "['item 1', 'item2', 'item 3']" I am interested in converting it to ...

Error occurs during server to server mutation with Apollo Client (query successful)

Currently, I am using apollo-client on my web server to interact with my graphql server (which is also apollo). While I have successfully implemented a query that retrieves data correctly, I encounter new ApolloError messages when attempting a mutation. Od ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Adjusting the empty image source in Vue.js that was generated dynamically

Currently experimenting with Vue.js and integrating a 3rd party API. Successfully fetched the JSON data and displayed it on my html, but encountering issues with missing images. As some images are absent from the JSON file, I've saved them locally on ...

Incorporate pictures from the popup onto the main page

I have developed a basic PHP image editor script where users can select images from galleries and merge them together. However, I am facing an issue: The galleries open in a popup while the editor area is on the parent page. I am looking for a JavaScript ...

Error occurs despite successful 200 response from Ajax delete request

I've been working on setting up a simple API for my project and encountered an issue. When I send a DELETE request using jQuery Ajax, the request goes through successfully, deletes the specified entry in the database, returns a status of 200, but trig ...

Is there a way to transfer the data from a chosen row into a different table?

My task involves using a table with two different conditions. In the first table, I display all incoming data. Then, in the second table (referred to as "select summary"), I want to show the row selected in the first table. To achieve this, I am utilizing ...