简体   繁体   中英

d3 error data is not defined

I have been stuck on this error for a while now and I cannot work it out. I have connected my d3.js to a database using a php file and I am working with a scatterplot visualization. On the connection to the php file everything is fine. Here is the relevant code:

d3.json("connection1.php", function(error, data){
data.forEach(function(d) {
    d['TITLE'] = d.TITLE.toString();
    d['YEAR'] = +d['YEAR']; 
    d['ABSTRACT'] = d.ABSTRACT.toString();
     console.log(d);
     })
});

But when I do this:

// don't want dots overlapping axis, so add in buffer to data domain   
xScale.domain([d3.min(data, xValue)-1, d3.max(data, xValue)+1]);
yScale.domain([d3.min(data, yValue)-1, d3.max(data, yValue)+1]);

I am getting the error

Uncaught ReferenceError: data is not defined

I am very new to d3 so if anyone can tell me how to overcome this error thank you in advance!

Please specify where are you using the data variable.

The variable 'data' only exists in the function, and you wont be able to refer it outside the block.

You can declare a variable '_data' globally or outside the php response function and copy the response 'data' to it. Then you can use the _data variable as required. Read more about it in closures, variable scopes, global variables etc.

var _data;
d3.json("connection1.php", function(error, data){
_data = data;
_data.forEach(function(d) {
    d['TITLE'] = d.TITLE.toString();
    d['YEAR'] = +d['YEAR']; 
    d['ABSTRACT'] = d.ABSTRACT.toString();
     console.log(d);
     });
 createGraph();
});

function createGraph() {
 /* code to create svg and other components goes here */
 xScale.domain([d3.min(_data, xValue)-1, d3.max(_data, xValue)+1]);
 yScale.domain([d3.min(_data, yValue)-1, d3.max(_data, yValue)+1]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM