Context
I'm building a WordPress Theme Template and am trying to pass an array of data from a Advanced Custom Fields > Repeater Field, using PHP and core WordPress functions, to a JavaScript / HTML5 pie chart.
The Problem
I don't know how to pass the PHP data to JS in a format JS understands.
The Questions
I'm not confident I'm asking the questions correctly, or thinking about the problem correctly. For example, I believe I can use JS to communicate directly with the database. But here's what I think the questions are:
- How do you pass a PHP array outside of a loop and into a format readable in JS?
- What are some links to training materials or courses on the subject?
Code
Here is my code:
<?php
if( have_rows('tpc_psmr_referrer') ):
while ( have_rows('tpc_psmr_referrer') ) : the_row();
$tpc_psmr_referrer_type = get_sub_field('tpc_psmr_referrer_type');
$tpc_psmr_referrer_platform = get_sub_field('tpc_psmr_referrer_type_platform'); // This needs to get passed as an array to the JS below.
endwhile;
endif;
?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2], // This is where the PHP array needs to be output.
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'Revenue'
};
var chart1 = new google.visualization.PieChart(document.getElementById('piechart1'));
chart1.draw(data1, options);
var data2 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'Budget'
};
var chart2 = new google.visualization.PieChart(document.getElementById('piechart2'));
chart2.draw(data2, options);
}
</script>