I have a question for my application logic in d3.js. I send an ajax request(some json data) from client to server and in the server(nodejs) I save into a file. Then I try to fetch json data via the following command.
d3.json("nodes.json", function(error, json) {
if(error)
{
console.warn('nodes.json error', error);
//throw error;
}
console.log("d3.json");
savedNodesLinks = json;
});
console.log('parsed', JSON.parse(JSON.stringify(savedNodesLinks || null)));
if(JSON.parse(JSON.stringify(savedNodesLinks || null)) != null)
{
links = JSON.parse(JSON.stringify(savedNodesLinks || null)).links;
nodes = JSON.parse(JSON.stringify(savedNodesLinks || null)).nodes;
}
This function which consists above-mentioned code snippet is called by a button. When I click the button first time, 'savedNodesLinks' variable shows as an undefined. When I push the button second time, data comes in a robust way. How can I fix this issue? I debugged the code but I couldn't find the problem
Thanks in advance,
console.log("d3.json")is called. At that point it is available. Meantime yourconsole.log()call after d3.json() is called (before your json is available), so savedNodesLinks is not yet defined. I would suggest reading up on asynchronous calls in javascript to better understand this.