Zero
Zero

Reputation: 76947

JSON output from PHP using d3.json

I created a PHP file to query JSON output. JSON output from the PHP file for a particular filter "testPHP.php?number=123" is

[{"source":"AB","target":"AC","type":"true"},{"source":"UB","target":"EP","type":"true"},{"source":"US","target":"UR","type":"lie"},{"source":"BS","target":"QW","type":"lie"},{"source":"UW","target":"EA","type":"lie"}]

I have tried this in html file to read the JSON output to links variable

var links; // a global
d3.json("testPHP.php?number=123", function(error, json) {
  if (error) return console.warn(error);
  links = json;
});

But, it seems like data is not stored in links. How do I store the data in var links?

Basically, I want to replace var links in this https://gist.github.com/mbostock/1153292 to that from JSON output from PHP.

EDIT: Or http://localhost:8080 is causing the problem?

Upvotes: 2

Views: 5030

Answers (2)

ben schwartz
ben schwartz

Reputation: 2589

The d3.json call is asynchronous; the code included after your callback is executed before the "links" variable has been populated.

var links; // a global
d3.json("testPHP.php?number=123", function(error, json) {
  if (error) return console.warn(error);
  links = json;

  console.log(links); // your links are populated here

  // include the rest of your app here
});

// links is still undefined here because the success callback hasn't been run yet

Upvotes: 2

user1890328
user1890328

Reputation: 1232

you would need to write links = [{"source":"AB","target":"AC","type":"true"},{"source":"UB","target":"EP","type":"true"},{"source":"US","target":"UR","type":"lie"},{"source":"BS","target":"QW","type":"lie"},{"source":"UW,"target":"EA","type":"lie"}]

At that point links will hold that information. You may however want to consider an array.

Upvotes: -1

Related Questions