Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
Ryan Avatar asked Feb 10 '13 04:02

Ryan


2 Answers

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>
like image 96
icktoofay Avatar answered Nov 10 '22 01:11

icktoofay


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>
like image 21
Sugarcaen Avatar answered Nov 10 '22 02:11

Sugarcaen