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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With