Mastering the art of transferring render :json => data to d3.js

I want to display the output of a JSON file as a d3.js graph, but I'm having trouble accessing the JSON data in my controller. Here is the relevant code:

First, let's take a look at the model:

class User < ActiveRecord::Base
  has_many :relationships
end

class User
  def self.including_relationships
    User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select("users.name, relationships.user_id, relationships.followsid,users.value").each_with_object(Hash.new{|h, k| h[k] =   []}) do |a, obj|
      obj['nodes'] << a.slice('name')
      obj['links'] << a.slice('user_id', 'followsid', 'value')
    end
  end
end

And here is the controller:

class UserController < ApplicationController
  def index
    render :json =>  User.including_relationships
  end
end

Finally, we have the index.html page:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Graph Display</title>
  <link href="stylesheets/style.css" rel="stylesheet" type="text/css" media="screen" />
  <script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<script>

var width = 960,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

// Make an AJAX call to fetch the JSON data from the controller
d3.json("user.json", function(error, graph) {
  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

  var link = svg.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag);

  node.append("title")
      .text(function(d) { return d.name; });

  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });
});
</script>
</body>
</html>

It seems that the issue lies with the line:

d3.json("user.json", function(error, graph) {

I need to change the reference to my JSON file, but I'm not sure how. Any suggestions would be appreciated.

Update

I have tried using AJAX to fetch the JSON data from the controller as suggested here:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Graph Display</title>
  <link href="stylesheets/style.css" rel="stylesheet" type="text/css" media="screen" />
  <script src="example.js"></script>
</head>
<body>
<script>
$.ajax({
  type: 'GET',
  url: 'localhost:3000/user',
  success: function(data) {
    var userJSON = data;
  }
})

var width = 960,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

d3.json(userJSON, function(error, graph) {
  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

  var link = svg.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag);

  node.append("title")
      .text(function(d) { return d.name; });

  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });
});

</script>

</body>
</html>

However, when I try this, all I see is the JSON result, and it doesn't get included in index.html.erb. I'm not sure why. Any advice would be greatly appreciated.

Answer №1

To interact with the endpoint, utilize AJAX query:

$.ajax({
  type: 'GET', 
  url: 'specific_url_here', 
  success: function(response) {
    var dataset = response;
  },
});

Afterwards,

d3.json(dataset, function(err, data) {

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

Transforming dynamic JSON data into SQL Server using Azure Data Factory

I've been attempting to flatten a dynamic JSON structure and insert the resulting data into a SQL Server table without success. I've explored several methods thus far: Copy Activity: The JSON data from a datab ...

A guide on efficiently deserializing the JSON response from an API using C#

Is there a way to create models from the JSON data, particularly if the data includes a string keyword name? The JSON Data: { "Meta Data": { "1. Information": "Intraday (5min) open, high, low, close prices and volume&q ...

Enhance your data table by updating the content without the need to refresh the entire page in CodeIgniter

Every time I update or insert data using the bootstrap modal form and ajax, the entire page reloads. Instead of refreshing the whole page, I want only the data table to be refreshed. Below is my ajax script: <script> $(document).ready(function( ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

The successful JSON response in an Ajax request is not functioning as expected

I've set up a data table that allows users to add rows by clicking the "plus" button. This triggers an ajax request to a URL with the rowId as a parameter (which corresponds to the specific row where the button was clicked). I expect to receive a JSON ...

Modifying several items with Ramda's lens

I am currently working with a data structure that is structured similarly to the following: var data = { "id": 123, "modules": [{ "id": 1, "results": [{ "status": "fail", "issues": [ {"type": "ch ...

Tips for presenting Nested JSON information?

I am having trouble figuring out the correct syntax to display DietName from Data{}, PartnerName from PartnerData[], and DayName from DayList[]. These data are inside another ArrayList, and I need help displaying them. { "Status": "1", "Message": " ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

"Encountering a strange issue where submitting a form with Jquery and AJAX in Rails does not work as expected, causing the index

Currently facing a unique issue with a jQuery/Ajax HTML update form. The application in question is a single-page TODO App that utilizes a Rails controller, where all changes to the DOM are made through jQuery/Ajax. After rendering the TODOs on the page v ...

The jQuery call to a web service is returning XML data, but the success function is receiving a

I have utilized: [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] The outcome of my web service call is: <string xmlns="http://tempuri.org/"> [{_pkId:"",_code:"",_message:"The file has been uploaded successfully.",_sta ...

During the installation process of json (1.8.1), an unexpected error arose, leading to Bundler being unable to proceed further

Encountered a problem while installing the json (1.8.1) package, preventing further progress for Bundler. Please ensure that gem install json -v '1.8.1' is successfully executed prior to bundling. xcrun: error: an incorrect active developer path ...

Loading Google Books JSON data into a ListView

Currently, I am utilizing the Google Books API to search for books. However, I am encountering an issue when trying to populate my ListView with the searched books as it is throwing an error specifically in the onPostExecute method, but I am unable to iden ...

Using JSON.load with a one-liner JSON isn't going to give you the desired result

I am dealing with JSON data that comes in two different formats - one is a single line, the other is formatted nicely. JSON A: {"id":1, "name":"BoxH", "readOnly":true, "children":[{ "id":100, "name":"Box1", "readOnly":true, "children":[ { "id":1003, "nam ...

Converting JSON to CSV with flexible array lengths: Harnessing the power of jq

I have retrieved a JSON data with the given structure { "type": "conversation", "id": "1234", "created_at": 1425586662, "initial_message": { "type": "initial_message", "id": "567", "body": "<p>Testing</p> ...

Exploring the Ins and Outs of Debugging JavaScript in Visual Studio Using

I encountered a peculiar issue while testing some code. When the program is executed without any breakpoints, it runs smoothly. However, if I introduce a breakpoint, it halts at a certain point in the JSON data and does not allow me to single-step through ...

Following the mongoimport process, the MongoDB database does not display any collections

Recently, I delved into the world of MongoDB and mapReduce, but encountered a hurdle along the way. The MongoDB installation went smoothly. Next, I attempted to import a json file by executing these 2 commands before launching mongo in the terminal (worki ...

Ways to populate select json keys with values from an array

I have the following array: [test, usera, test, userb, test, userc, test, userd] This is my JSON: { "data": [ { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9bdacbabdbcbaacbba889a8abaae7aaa6a4">[em ...

Tips for inserting multiple JSON data links into Mysql

How can I efficiently extract JSON data from multiple links and save it into a MySQL database? Is there a way to modify the code below to enable reading from several URLs? <?php //connect to mysql db $con = mysql_connect("username","password", ...

Encountering a 400 error while making a Python request that involves

Below is the code I am using to register a user through an API endpoint: import argparse import requests import ConfigParser import json import sys import logging # Configuration Parameters env = 'Pre_internal' Config = ConfigParser.ConfigPar ...

Issues arise with the npminstall function within custom Yeoman generators

I've been researching various tutorials on how to create a custom Yeoman generator. Here's the code snippet in question: runNpm: function(){ var done = this.async(); this.npmInstall("", function(){ console.log("\nEverything Setup !!!&b ...