As a JQUERY/d3-noob, it seems I cannot figure out how to make this work:
supdog = d3.json(dataPath, function(jsondata){
return jsondata;
})
console.log(supdog);
Thanks in advance.
The function d3. json() is an asynchronous function that directly returns (with an undefined value I assume). Only when the data is received from the backend, the callback function you passed to it will be called.
d3. csv() returns the data as an object. This object is an array of objects loaded from your csv file where each object represents one row of your csv file.
Syntax: d3. json(input[, init]);
Besides the fact that your problem description is very terse, the problem seems to be your assumptions about what is returning what.
The function d3.json() is an asynchronous function that directly returns (with an undefined value I assume). Only when the data is received from the backend, the callback function you passed to it will be called. Obviously the context is different here and the return value of your callback will not automatically become the return value of d3.json (as this one has returned "long" before already).
What you want to do is probably something like:
var jsondata;
d3.json(dataPath, function(dataFromServer) {
jsondata = dataFromServer;
}
console.log(jsondata);
Update 1: Obviously, the above example is still not fully correct. The call to console.log() is made directly after the d3.json() returned. Thus, the server might not have sent the reply fully yet. Therefore, you can only access data when the callback is returned. Fixed example:
var jsondata;
function doSomethingWithData() {
console.log(jsondata);
}
d3.json(dataPath, function(dataFromServer) {
jsondata = dataFromServer;
doSomethingWithData();
})
For a (somewhat stupid, but) working example see: http://jsfiddle.net/GhpBt/10/
Update 2: The above example demonstrates in which order the code is executed but does not really deserve a price for most beautiful code. I myself would not use this "global" variable and simplify the above example to:
function doSomethingWithData(jsondata) {
console.log(jsondata);
}
d3.json(dataPath, doSomethingWithData);
Note how doSomethingWithData is directly passed to d3.json in stead of calling it separately in an anonymous inner function.
Note: This is not a particular problem of d3.js. Basically, all javascript functions that are asynchronous are likely to behave in a similar way. If they return something, it will not be the return value of the passed callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With