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

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
jvdh
  • 612
  • 1
  • 6
  • 19

1 Answers1

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.

Pablo Navarro
  • 8,244
  • 2
  • 43
  • 52
  • 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 May 29 '13 at 00: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. – Pablo Navarro May 29 '13 at 00:18
  • Thanks for pointing that out, I improved the answer using your suggestion. – Pablo Navarro May 29 '13 at 00:33
  • Thanks, that explains it. I was also made aware of this post by Mike Bostock: http://stackoverflow.com/questions/9491885/csv-to-array-in-d3-js/9492055#9492055 – jvdh May 29 '13 at 07:40