var dataset = [ 5, 10, 15, 20, 25 ]; d3.select("body").selectAll("p") ...">

Bringing data from PHP to D3.JS

I have it:

<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 learn 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.'; } ?> 

This works with the rest and displays some random event names such as movies, purchases, work.

I found this tutorial on how to transfer PHP variables to 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 it. This is my last attempt:

  <?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 that maybe the array would work, so I 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 no luck. Can someone offer me some tips or point me to a tutorial on how to get data from PHP in Javascript?

+4
source share
2 answers

Try using the PHP json_encode function , and then paste the data:

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

I understand that this is a bit late for the party, but you cannot include php in .html files and successfully parse it unless your server is configured for this.

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> 
+3
source

All Articles