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

Is it possible to use a webcam to scan a QR code directly into a webpage?

Is it possible to enable users to input data on a webpage using QR code scanning? I'm unsure if there is a tool that can be integrated into the page or paired with a library to make this happen, or if I need to consider an external solution beyond th ...

Error: [Errno 22] occurred while attempting to read a JSON file with .read() method

I'm currently facing an issue while attempting to read a JSON file in Python. The file 'Books_5.json' is located in the Downloads folder, where I am operating from. However, when I try to utilize the .read() function, I encounter the followi ...

Angular checkboxes not triggering ng-click event

Within my Angular application, there is a form that includes checkbox inputs: <div ng-repeat="partner in type.partners"> <label class="checkbox-inline"> <input type="checkbox" value="partner" ng-checked="report.participa ...

Fixed position not being maintained after clicking the button

Looking for some help with a fixed header issue on my website. The header is supposed to stay at the top while scrolling, which works well. However, when I switch to responsive view, click the menu button, and then go back to desktop view, none of the po ...

Load suggestions from Material UI AutoComplete dynamically based on user input

I am facing a challenge with an Autocomplete component that needs to handle a large data list, up to 6000 elements, and display suggestions based on user input. Due to the sheer number of options, when a user types on a slower computer, there is a noticeab ...

Building routes for a stationary website with Angular

Currently, I am in the process of developing a static site using a combination of HTML, CSS, and JS along with nodeJS and express for server-side functionality... One challenge I am facing is setting up routes to display pages like /about instead of acces ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

Detecting changes in parent ref with Vue's v-modelIs this

I am struggling to implement two-way binding because I can't determine if the model ref is being changed by the parent or child component. Using watch captures all changes without any indication of the source of the change. <script setup> // Pa ...

Clear out all current cookies

I utilized the following JavaScript code to generate a pop-up window on the website that would only appear once. However, my client now wants to launch a new promotion and I am attempting to remove existing cookies so that the pop-up window displays again ...

What are the steps to resolve the Syntax Error that occurs while running Dev with Vite?

error occurred while starting development server: SyntaxError: Unexpected end of JSON input. I have verified that my JSON is valid using JSONlint. Additionally, I am encountering the following error messages: error when initiating dev server: SyntaxError: ...

How to Populate Object Literal with Multiple Objects in AngularJS

When I click on "Evan", I receive the following response: {"id":1,"name":"Evan"} If I click on "Robert", I will get: {"id":2,"name":"Robert"} Is there a way to modify this code so that it follows the aforementioned steps and generates an object similar ...

"Sending the selected pass selector as a parameter to the dispatched action is causing a typing

When a selector changes its value, I want to trigger an action. To achieve this, I passed the selector with a subscription instead of passing an observable. selectedSchedulingsOnPopup$ = this.store.pipe(select(selectSchedulingsByBranch)); this.store.disp ...

Check input validations in Vue.js when a field loses focus

So I've created a table with multiple tr elements generated using a v-for loop The code snippet looks like this: <tr v-for="(item, index) in documentItems" :key="item.id" class="border-b border-l border-r border-black text ...

Bidirectional Communication between ExpressJS and Mongoose Models

Let's consider a scenario where we have a User model and a Book model in our express app, both referencing each other. How can mongoose middleware be utilized to ensure that both models stay synchronized when saving either one? It would be beneficial ...

Switching Unicode icon when element is clicked

My form has two inputs - one for text input and the other for submitting, like a button. I have added an icon to the submit button and want it to change when clicked. <input class="searchBtn" id="submit" name="submit" type="submit" value="&#xf002"& ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

Is it necessary to have both index.js and Component.js files for a single component in React?

Continuously analyzing various projects, I often come across authors who organize their file structures in ways that are perplexing to me without proper explanation. Take, for instance, a component where there is a folder named Header. Inside this folder, ...

Using JavaScript to search for a specific string within a row and removing that row if the string is detected

I need help with a script that removes table rows containing the keyword STRING in a cell. However, my current script is deleting every other row when the keyword is found. I suspect this has to do with the way the rows are renumbered after deletion. How c ...

Setting the column width and border-top in Highcharts

Hey there, I'm facing an issue with my highcharts diagram. 1) Can anyone help me adjust the column width to match the width of the month area? (I've tried changing "width" in CSS but it's not working) 2) Also, how can I remove all borders ...

Interactive table with Draggable feature supported by Bootstrap Vue

After tirelessly searching for a solution to drag and drop rows on a Bootstrap Vue table, I finally stumbled upon a functional version here: Codepen I attempted to integrate this code into my own table: Template: <b-table v-sortable="sortableOptions ...