0

I have done a lot R&D, tried lots of question on stackoverflow and from other site too but unable to understand what i am doing wrong. I will be really thankful if help me to point where i am wrong.

Also tried this too if code is skipping before response but not use. Returning array from d3.json()

D3 code

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
    d3.json("chart_data.php", function(error, data){
        json_Data = data;
        console.log("Error:"+error);
        console.log(json_Data);
    });
</script>
</body>
</html>

Console for error is

Error:SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Console for data is

undefined

If I run php file direct in browser I am getting:

[{"value":"1","date":"2016-03-29"},{"value":"0","date":"2016-03-30"},{"value":"3","date":"2016-03-31"},{"value":"2","date":"2016-04-01"},{"value":"2","date":"2016-04-02"},{"value":"5","date":"2016-04-03"},{"value":"1","date":"2016-04-04"},{"value":"1","date":"2016-04-05"},{"value":"0","date":"2016-04-06"}]

This is my PHP

<?php
require 'db_connection.php';
$sql = "SELECT `y-axis` as value, `x-axis` as date FROM site_data";
$result = $con->query($sql);
$data = array();
if ($result->num_rows > 0) {
    $count = 0;
    while($row = $result->fetch_assoc()) {
        $data[$count]['value'] = $row['value'];
        $data[$count]['date']  = $row['date'];
        $count++;
    }
}
echo json_encode($data);
$con->close();
?>

DB connection file

<?php
$con = mysqli_connect("localhost","root","","analytic");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

PHP file and D3 file is on same directory.

Community
  • 1
  • 1

1 Answers1

0

Instead of passing a .php file as a parameter to d3.json() try passing a .json file:

d3.json("chart_data.json", function(error, data){
    json_Data = data;
    console.log("Error:"+error);
    console.log(json_Data);
});

Use php to get the code from the DB and convert it to json using something like json_encode. Output that data in a .json file. Don't try to read json directly from a .php file.

neuquen
  • 3,991
  • 15
  • 58
  • 78
  • Are you asking me to write JSON file via PHP and then I can read JSON file. I have option to write tsv file too but i was wondering why it is not working like that. anyways thanks for your help I will vote up once I will make this – Farhan Baloch Apr 07 '16 at 00:23
  • For now, just try creating a separate .json file manually to test. Only put the json in it and call it. If it works then you know what the problem is. If not, back to the drawing board. – neuquen Apr 07 '16 at 00:27
  • Everything was ok issue was with my machine :). Anyways this solution is also good – Farhan Baloch Apr 12 '16 at 19:57