2

my code is working in the console, but not when loading the website.

function getData() {
    var a = [];
    d3.csv("../csv/master.csv").get(function (error, rows) {
        for (var i = 0; i < rows.length; i++) {
            a.push(rows[i]);
        }
    });
    return a; 
}
a = getData();
alert(a[0].agency);

Strangely, the variable a seems to be loaded by the website as I can call it in the console, but the alert throws an error.

("Uncaught TypeError: Cannot read property 'agency' of undefined")

When I call the exact same alert in the console, however, it works perfectly.

Any ideas?

Thanks,

Jonas

4

1 Answer 1

4

The d3.csv method issues an asynchronous request, so it is possible that in the website version, the csv file hasn't been fully loaded yet when you try to access the data. You should probably reorganize your code and put the logic that depends on the data inside the callback function. You could also trigger an event when the data loading is done and have another object listening to that event to begin the drawing.

d3.csv('../csv/master.csv', function(error, rows) {
    // The data is available here
    alert(rows[0].agency);
});

More information about d3.csv in the docs.

EDIT: As @elclanrs pointed out, the previous code failed to explain that the posted code needs to be reorganized, so I updated the answer.

4
  • 1
    But you'd have to run that if statement in an interval until ready==true otherwise it'll check once, it'll be false, and won't check again. The proper way is to re-organize the code to use the callback that's provided by the asynchronous request.
    – elclanrs
    Commented May 29, 2013 at 0:16
  • Of course. Another strategy would be to trigger an event when the data is ready and having another object listening to that event to begin the drawing. Commented May 29, 2013 at 0:18
  • Thanks for pointing that out, I improved the answer using your suggestion. Commented May 29, 2013 at 0:33
  • Thanks, that explains it. I was also made aware of this post by Mike Bostock: stackoverflow.com/questions/9491885/csv-to-array-in-d3-js/…
    – jvdh
    Commented May 29, 2013 at 7:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.