1

I'm trying to use php to connect postgres and visualize the data with d3.js. I encoded the data to json successfully, but when I want to load the data by using d3.js, there's a SyntaxError: Unexpected token < in JSON at position 0(…) index.html:12 undefined.

Here is my code for php:

$db_connection = pg_connect("host=localhost dbname=xxx user=xxx     password=xxx");
    $result = pg_query($db_connection, "SELECT * FROM taxi_stats.satisfy");
    $data = array();
    while ($row = pg_fetch_array($result))
    { 
      $data[] = $row;
    } 
    echo json_encode($data);
    pg_close($db_connection);

For d3.js

<script>
d3.json("data.php", function(error, data) {
    if(error){
        console.log(error);
    }
    console.log(data);
});
</script>
Benran Fan
  • 13
  • 4
  • 'SyntaxError: Unexpected token < ' : In my experience and of those in the answers here, that's a php error or warning getting echo'ed back to the javascript instead of json. Check your php_error.log. http://stackoverflow.com/questions/18561556/syntax-error-unexpected-token – mgraham May 13 '16 at 20:30

2 Answers2

0

Change the header content type from 'text/javascript' to 'text/html'.

Or it could be the error that one of the token '>' is not wrapped with single or double quotes.

Murlidhar Fichadia
  • 2,589
  • 6
  • 43
  • 93
  • It doesn't work for me and I have no error in encoded json. When I copy and paste the encoded json to a json file and use d3 to load it, I can get the data successfully. I think something happens when loading php as the data source. – Benran Fan May 13 '16 at 21:36
0

Finally I figured it out. Add one line of php header('Content-type: application/json; charset=utf-8'); works for me.

Benran Fan
  • 13
  • 4