1

I am attempting GET a JSON from a URL based on a link and send that JSON object to be used by my D3 graph. The URL leads directly to the JSON. However, I am getting an error root.links.forEach is undefined. The code works when I am sending in a JSON locally but not through the AJAX request. Not sure why root.links.forEach being undefined is the error I receive.

Code:

var width = innerWidth,
    height = innerHeight,
    color = d3.scale.category20(),
    root;

... (random code) ...

$.ajax({
type: "GET",
url: url + key,
crossDomain: true,
async: true,
dataType: "json",
success: function(data) {
    root = data;
    update();
}
});

function update() {

// sets the source and target to use id instead of index
var edges = [];
root.links.forEach(function(e) {

... (rest of code) ...

If I take away the AJAX call and replace it with this then it works...

d3.json("/path/to/json.json", function(error, json) {
    // expands scope of json
    root = json
    update();
});
Joey
  • 1,724
  • 3
  • 18
  • 38
  • Use jsonp as the datatype. Please review the differences here and why it is used instead of json: http://stackoverflow.com/questions/2887209/what-are-the-differences-between-json-and-jsonp – Ben Sewards Apr 29 '15 at 18:30
  • What if I cannot modify the JSON data at the URL I am hitting? Would just changing the data type from "json" to "jsonp" in my request have the effect? – Joey Apr 29 '15 at 18:45
  • You can't do crossdomain AJAX without JSONP or CORS, in which jsonp needs to be supported by the server. If it does, the only change on the Client side with JSONP is to add a callback parameter to the URL. On the Server you need to get the 'callback' parameter and, instead of returning the raw JSON, you wrap that string in a function definition. – Ben Sewards Apr 29 '15 at 19:06

0 Answers0