I encountered an issue with reading my json file while working with d3js, resulting in an error

XMLHttpRequest failed to load

file:///C:/Users/HP/Desktop/tree.json
. Requests across different origins are only permitted for certain protocol schemes:
http, data, chrome, chrome-extension, https, chrome-extension-resource
.

My code:

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<style>
text {
font-family:"Helvetica Neue", Helvetica, sans-serif;
}
.name {
font-weight: bold;
}
.about {
fill: #777;
font-size: smaller;
}
.link {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
</head>

<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {
top: 0,
right: 320,
bottom: 0,
left: 0
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var tree = d3.layout.tree()
.separation(function(a, b) {
return a.parent === b.parent ? 1 : .5;
})
.children(function(d) {
return d.parents;
})
.size([height, width]);

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.json("tree.json", function(error, json) {
if (error) throw error;

var nodes = tree.nodes(json);

var link = svg.selectAll(".link")
.data(tree.links(nodes))
.enter().append("path")
.attr("class", "link")
.attr("d", elbow);

var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});

node.append("text")
.attr("class", "name")
.attr("x", 8)
.attr("y", -6)
.text(function(d) {
return d.name;
});

node.append("text")
.attr("x", 8)
.attr("y", 8)
.attr("dy", ".71em")
.attr("class", "about lifespan")
.text(function(d) {
return d.born + "–" + d.died;
});

node.append("text")
.attr("x", 8)
.attr("y", 8)
.attr("dy", "1.86em")
.attr("class", "about location")
.text(function(d) {
return d.location;
});
});

function elbow(d, i) {
return "M" + d.source.y + "," + d.source.x + "H" + d.target.y + "V" + d.target.x + (d.target.children ? "" : "h" + margin.right);
}
</script>  

<p>JSON data:</p>

<pre><code>
{
"name": "Clifford Shanks",
"born": 1862,
"died": 1906,
"location": "Petersburg, VA",
"parents": [{
"name": "James Shanks",
"born": 1831,
"died": 1884,
"location": "Petersburg, VA",
"parents": [{
"name": "Robert Shanks",
"born": 1781,
"died": 1871,
"location": "Ireland/Petersburg, VA"
}, {
"name": "Elizabeth Shanks",
"born": 1795,
"died": 1871,
"location": "Ireland/Petersburg, VA"
}]
}, {
"name": "Ann Emily Brown",
"born": 1826,
"died": 1866,
"location": "Brunswick/Petersburg, VA",
"parents": [{
"name": "Henry Brown",
"born": 1792,
"died": 1845,
"location": "Montgomery, NC"
}, {
"name": "Sarah Houchins",
"born": 1793,
"died": 1882,
"location": "Montgomery, NC"
}]
}]
}

Answer №1

When examining your code, I noticed that you are using

d3.json("tree.json", function(error, json)
, which utilizes the HTTP GET method. The error you are encountering is likely due to directly opening HTML documents from your browser without a proper HTTP Web Server to serve the JSON file.

If you wish to run your code without a server and avoid the Get Request, you can do so by following this alternative approach:


          var json = {
            "name": "Clifford Shanks",
            "born": 1862,
            "died": 1906,
            "location": "Petersburg, VA",
            "parents": [{
              "name": "James Shanks",
              "born": 1831,
              "died": 1884,
              "location": "Petersburg, VA",
              "parents": [{
                "name": "Robert Shanks",
                "born": 1781,
                "died": 1871,
                "location": "Ireland/Petersburg, VA"
              }, {
                "name": "Elizabeth Shanks",
                "born": 1795,
                "died": 1871,
                "location": "Ireland/Petersburg, VA"
              }]
            }, {
              "name": "Ann Emily Brown",
              "born": 1826,
              "died": 1866,
              "location": "Brunswick/Petersburg, VA",
              "parents": [{
                "name": "Henry Brown",
                "born": 1792,
                "died": 1845,
                "location": "Montgomery, NC"
              }, {
                "name": "Sarah Houchins",
                "born": 1793,
                "died": 1882,
                "location": "Montgomery, NC"
              }]
            }]
          };

          var margin = {
                          top: 0,
                          right: 320,
                          bottom: 0,
                          left: 0
                      },
                      width = 960 - margin.left - margin.right,
                          height = 500 - margin.top - margin.bottom;

                  var tree = d3.layout.tree()
                      .separation(function(a, b) {
                        return a.parent === b.parent ? 1 : .5;
                    })
                      .children(function(d) {
                        return d.parents;
                    })
                      .size([height, width]);

                  var svg = d3.select("body").append("svg")
                      .attr("width", width + margin.left + margin.right)
                      .attr("height", height + margin.top + margin.bottom)
                      .append("g")
                      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


                      var nodes = tree.nodes(json);

                      var link = svg.selectAll(".link")
                          .data(tree.links(nodes))
                          .enter().append("path")
                          .attr("class", "link")
                          .attr("d", elbow);

                      var node = svg.selectAll(".node")
                          .data(nodes)
                          .enter().append("g")
                          .attr("class", "node")
                          .attr("transform", function(d) {
                            return "translate(" + d.y + "," + d.x + ")";
                        })

                      node.append("text")
                          .attr("class", "name")
                          .attr("x", 8)
                          .attr("y", -6)
                          .text(function(d) {
                            return d.name;
                        });

                      node.append("text")
                          .attr("x", 8)
                          .attr("y", 8)
                          .attr("dy", ".71em")
                          .attr("class", "about lifespan")
                          .text(function(d) {
                            return d.born + "–" + d.died;
                        });

                      node.append("text")
                          .attr("x", 8)
                          .attr("y", 8)
                          .attr("dy", "1.86em")
                          .attr("class", "about location")
                          .text(function(d) {
                            return d.location;
                        });
                   ;

                  function elbow(d, i) {
                    return "M" + d.source.y + "," + d.source.x + "H" + d.target.y + "V" + d.target.x + (d.target.children ? "" : "h" + margin.right);
                  }
        
      

          <script src="http://d3js.org/d3.v3.min.js"></script>
        
      

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

Access the MySQL database using PHP within JavaScript and specifying a specific time interval

My goal is to periodically query a MySQL database using an external PHP script. I want this script to run every 2 seconds, triggered by a javascript (jquery, flot) interval setup: <script type='text/javascript'> var data = []; var ...

Locate and extract JSON information from a character string using R

Looking for a function that can identify valid JSON data within a mixed character string. My Current Understanding It is known that jsonlite::fromJSON() can parse JSON data as demonstrated below: library(jsonlite) json_glob_1 <- "{ \"age\" ...

Is it possible to permanently alter HTML values with JavaScript?

Can a html value be permanently modified using javascript? I am trying to edit a local file. Below are the codes I'm using: function switchPic(){ top.topPage.activeDef = top.topPage.document.getElementById('h1'); top.topPage.activeDef. ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

When comparing object strings, it is important to consider the differences between stringifying identity operators

While working on a reactjs component, my colleague encountered an issue with identity operators and JSON.stringify(). I was puzzled as to why he used stringify in the code, but what really confused me was why the if/else blocks were not functioning properl ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

What is the best way to extract targeted JSON data from a REST API with Node.js?

I am struggling to retrieve JSON data for a specific match, let's say match=2, from a collection of matches stored in MongoDB. Here is a sample of the JSON response: { "_id": "5a63051735aaddd30d1d89cc", "id": 1, "season": 2008, "city ...

Tips for typing the following object/type in TypeScript

I need help with typing a user state in my application. I have the following: a user type which includes id, email, firstName, lastName, and verified fields. export type User = { id: string | null; email: string | null; firstName: string | null; l ...

Choose a specific cell from a table and then include it in a submission through a form

My jQuery-generated table consists of 3 td cells, each containing 10 values retrieved from the server. I need to choose one value from these to include in a form submission. What is the best way to achieve this? ...

I am experiencing issues with the detection of mouseover events on an SVG circle

I am currently working on a d3 map with zoom functionality that displays circles representing different cities. However, I am facing an issue where the mouseover event for the circles (which shows tooltips and clicking reveals some lines) seems to only reg ...

Customizing the Zoom Control Style in Vue Leaflet

I'm currently working on developing a Map App in Dark Mode using Vue, but I've encountered an issue with changing the style of the Zoom Control. Here's what I have tried so far: template> <div class="main-map"> <l ...

Tips for automatically scrolling images horizontally in responsive layouts

Recently, I've been working on a website called . On the homepage, my portfolio images are arranged in a grid format using the <li> tag. I'm looking to align them side by side and have them scroll horizontally automatically, preferably with ...

Issues with jQuery '.ajax()' requests falling short

I'm currently attempting to make a jQuery .ajax() call to a public web service, but I seem to be struggling with finding the correct syntax. I've experimented with various implementations. For example: $.ajax({ url: 'http://www.geognos.c ...

Issue with image not loading on Next [email protected] while utilizing Image component from next/image along with tailwindcss class

I am trying to make my image responsive on mobile view. I have used tailwindcss classes to set the Image className, and it works fine when I only use reactjs or a regular img tag. I am attempting to make this image responsive. I have tried setting the layo ...

Tips for utilizing the "g" element in SVG within CoffeeScript to rotate an object in D3

I'm experimenting with creating a design similar to the following SVG code snippet: <svg width="12cm" height="4cm" viewBox="0 0 1200 400" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>Example rect02 - rounded rectangles&l ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

Sails.js navigating through sessions

What is a rolling session in Sails.js? A rolling session is a session that expires after a set amount of time without user activity, except for websockets live updating data. If the user navigates to a different part of the site before the session expires, ...

How to implement a service function to handle $http responses in a controller

Is it possible to use $http only for my service and not the controller? I am getting undefined in my console.log when trying to display data in a $scope. Here is my code: app.controller('adminControl', ['$scope','$routeParams&apo ...

Loading images incrementally using promises

Attempting to load images with different resolutions sequentially using promises. Even after making changes as per the first suggestion, only one image is getting loaded according to Chrome dev tools. function loadImage(src) { return new Promise(fun ...

Sending various values via a click in an HTML link

Hello, I am attempting to pass multiple values using the HTML onclick function. I am utilizing Javascript to generate a table dynamically. var user = element.UserName; var valuationId = element.ValuationId; $('#ValuationAssignedTable').append(&a ...