I read a lot of posts here about how to save my data in a variable. To do so I created the global variable \"arraydates\". It needs to be in an array to be used for the axis tic
Yes — it's the asynchronous nature of ajax requests that affecting what's being console logged. Code that lives outside (and after) the d3.json
handler function will execute immediately after the ajax request is initiated but before the response comes back. The link Lars posted above covers all that, but the implication is that you need a global variable, or that any code you want to run after the data is ready has to live inside the d3.json
handler function. If you're looking for a cleaner pattern that's slightly less spaghetti -ish and doesn't depend on a global variable, you can set it up like so:
d3.json("/weather/date.json", function(error, datad) {
var array = [];
for(var i in datad) {
array.push( datad[i].date);
}
// Call a rendering function, passing in the results
// of the ajax call (plus the processing). No need for
// global variables.
renderMyVisualization(array);
});
function renderMyVisualization(arrayDates) {
// When this code runs, we have the data and you're
// ready to render
d3.selectAll("div").data(arrayDates)
...
}