joseph_pindi
joseph_pindi

Reputation: 867

PHP-generated json variables not showing in D3.js

I've tried a few variations of this code, but I'm getting stalled with no error message in the Console. Right now, it should be pretty straightforward and cribbed mostly from Getting Started with D3.js by Mike Dewar. I made some changes which I think are making it bomb out (sorry, Mike, I'm sure this is my bad).

First of all, I have a php file that works when I open it: {"name":1,"status":2,"url":3,"time":4,"day":5}

The code that echoes it is called 'jsonphp.php':

<?php
    $arr = array('name' => 1, 'status' => 2, 'url' => 3, 'time' => 4, 'day' => 5);
    echo json_encode($arr);
?> 

Then I simply want to reference it and (as a test) show it in a table. Here is a file called 'd3test.htm'

<!DOCTYPE html>
<html>
    <head>
        <meta charset = 'utf-8'>
        <script src='d3.v2.min.js'></script>
        <script>
        function draw(data){
            'use strict';
            d3.select('body')
                .append('ul')
                .selectAll('li')
                .data(data)
                .enter()
                .append('li')
                .text(function(data){
                    return data.name + ': '+ data.status;
                });
        }
        </script>
    </head>
    <body>
        <script>
            d3.json('jsonphp.php', draw);
        </script>
    </body>
</html>

I tried a few variations, like renaming the json headers, trying to get the 'draw' function along a variable (yeah, I kind of knew that wouldn't work) and I think maybe D3.js doesn't like the fact that the file ends in 'php'? Not getting an error returned says to me that it thinks it is working, so maybe that's not it. This should be so straightforward and I know if I can get this going I can execute more complicated outputs, but it's just that first step of a thousand-mile journey. BTW tried running this in IE 9 and Safari 5.1.7 and it is the same result. Thanks in advance!

ADDENDUM DEC 5: I tried alerting back the length of the jsonphp.php file in my html document and got 'undefined'. However I try it with another test file with a js extension and nothing in it but this ([{"a":"-1.14","b":"4.14"},{"a":"-0.13","b":"1.38"},{"a":"-4.19","b":"1.43"},{"a":"-0.21","b":"3.34"}]) and it alerted back the correct number (4). Also using the test I got the visualization to work ok. So the problem is that either D3.js does not like the php file, or something is the matter with the php file, even though it looks ok.

Upvotes: 0

Views: 953

Answers (1)

skyronic
skyronic

Reputation: 1635

Try setting the Content-Type header in PHP:

header("Content-Type: application/json");

before you call json_encode

Upvotes: 1

Related Questions