Prakash Patil
Prakash Patil

Reputation: 13

How to pass data to d3.json()

Currently the code is working perfect. It's just that I want a different tree chart for each user. So I have to pass $user in getData.php so that the json data get created according to this user and then the chart. $user is used in mysql select statements in getData.php to select data from database and this selected data is then converted into json.

Please tell me how do I pass $user as a callback in which d3 function. I am out of my resources!!

var queryString = window.location.search;
var url = "d3js/getData.php" + queryString;
d3.json(url, function(error, treeData) {
    console.log(treeData)
    root = treeData[0];
    update(root);
});

At the end of the getData.php there is

header('Content-Type: application/json');
echo json_encode($tree);

So I guess the output of the php file is json data

Upvotes: 1

Views: 2350

Answers (5)

Sampath  G
Sampath G

Reputation: 1252

d3.json function is used to get the data from a json file which doesn't work for PHP files which returns response other than json format.

You can use d3-request API. On call back - you can render your graph: Example:

var url = "d3js/getData.php" + window.location.search;
d3.request(url)
.get(function(error, treeData) {
   console.log(treeData)
   root = treeData[0];
   update(root);
});

Reference: https://github.com/d3/d3-request/blob/master/README.md#request

For more details - https://github.com/d3/d3/blob/master/API.md

Upvotes: 1

Aman Jain
Aman Jain

Reputation: 2582

You can also use the function to get map your values:

 d3.layout.stack()(['value'].map((value) => {
  return data.map((d: any) => {
    return { x: obj[d.xAxis], y: d.value };
  });
}));

You can also see more example here-

https://github.com/amanjain325/angular-d3-charts

Upvotes: 0

Oliver Houston
Oliver Houston

Reputation: 323

The code I use is:

function upL(l_id) {
d3.json("lsel.php?l_id=" + l_id, function(error, gr) {
     if (error) {
        return console.error(error)
    } else
        console.log(gr);
        draw(gr)
}).header("Content-Type", "application/x-www-form-urlencoded")//this bit might be necessary
}

function draw(gr){create graph...}

(l_id is a user selected variable)

So yours looks OK, try adding the content-type (.header(...)) and if treeData is being logged to the console, the problem might be the way you're accessing it.

Upvotes: 0

ofey
ofey

Reputation: 3327

For a start you need to export your data to a json file such as data.json

d3.json() will expect a json file not a php file.

 d3.json("data.json", function(error, data) {
      if (error) throw error;
      ...
});

Upvotes: 0

Related Questions