Ryan
Ryan

Reputation: 709

Bringing data from PHP into D3.JS

I have this:

<script type="text/javascript">
var dataset = [ 5, 10, 15, 20, 25 ];

        d3.select("body").selectAll("p")
            .data(dataset)
            .enter()
            .append("p")
            .text("New paragraph!");
</script>

It works. Then I've been learning MySQL/PHP and have some data in a tiny database.

<?php
if ( $results ) {
foreach($results as $row) {
    echo $row->eventName . "<br>";
}
} else {
echo 'No rows found.';
}
?>

That works with the rest of it and displays some random event names like Movies, Shopping, Work.

I found this tutorial on how to bring PHP variables into Javascript but can't figure it out. To simplify instead of trying to figure out the array I even switched to just trying to figure out the data itself but couldn't even get that. This is what my last attempt was:

    <?php
$php_var = 1;
?>

<script type="text/javascript">
var dataset = <?php echo $php_var; ?>

        d3.select("body").selectAll("p")
            .data(dataset)
            .enter()
            .append("p")
            .text("New paragraph!");
</script>

And then I thought maybe an array would work so tried this

<?php
$php_var = array(
    5, 10, 15, 20, 25);
?>

<script type="text/javascript">
var dataset = $php_var

        d3.select("body").selectAll("p")
            .data(dataset)
            .enter()
            .append("p")
            .text("New paragraph!");
</script>

But also had no luck. Could anyone offer me some advice or point me towards a tutorial on how to get data from PHP into Javascript?

Upvotes: 5

Views: 13651

Answers (2)

Sugarcaen
Sugarcaen

Reputation: 90

I realize this is a little late to the party, but you can't include php on .html files and have it successfully parsed unless your server is set up to do so.

You need to add one of the following snippets to your .htaccess:

RemoveHandler .html .htm
AddType application/x-httpd-php .php .htm .html

or

<FilesMatch "\.html$">
ForceType application/x-httpd-php
</FilesMatch>

Upvotes: 3

icktoofay
icktoofay

Reputation: 129059

Try using PHP's json_encode function, and then embedding the data:

<?php
    $dataset = array(5, 10, 15, 20, 25);
?>
<script>
    var dataset = <?php echo json_encode($dataset); ?>;
    // ...
</script>

Upvotes: 6

Related Questions