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!

1 Answer

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]); } 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like