-1

I am using following code to read data from json using D3 and passing this to another function.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple venn.js example</title>
</head>
<style>
div {
    max-width: 300px;
    height: 400px;
    margin: 0 0 0 0;
    padding: 0 0 0 0;
}
</style>
<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="../venn.js"></script>


<script>
    var sets= [{}];
    d3.json( "json", function( data ) 
    {  
       sets=data;        // reading successfully
    });

    alert(sets);    // but i need to use alert to pass the value to function div.datum(sets) otherwise sets value is null.
    var div =d3.select("#weighted_example")
    div.datum(sets).call(venn.VennDiagram())
</script>
</html>

json file:

[ { "sets": [0], "size": 1958 }, { "sets": [1], "size": 1856 }, { "sets": [2], "size": 1297 }, { "sets": [0, 1], "size": 220 }, { "sets": [2, 0], "size": 123 }, { "sets": [2, 1], "size": 139 } ]

logically it seems to unrealistic. When i use alert in the d3.json() function it shows the correct values so sets values already been assigned but why null values are passed if i don't use alert for sets. How can i fix such error?

man data
  • 43
  • 2
  • 8

1 Answers1

1

d3.json is an asynchronous function, thus you can not be sure that sets will be ready when you arrive at the div.datum line.

The reason why you see it working with alert is because alert will stop the flow of your javascript, thus sets will have had a value attributed.

You should put your datum code inside the d3.json code.

MisterJ
  • 919
  • 1
  • 9
  • 24