I want to add interactivity to my Google Chart. I am planning to use addListener to my Google Chart so that when users click on the pie chart, it will draw up another chart. I'm not very familiar with Google Visualization and pretty bad in practical skills for coding, hence I wanted to make sure I can make the example provided by Google works before proceeding on drawing up another chart.
However, when I followed the partial code snippet example provided in Google developer docs, the chart does not appear in my webpage. The data is taken using PHP from MySQL database.
Here is my code for the chart.
//Chart (Hardest Topics decided by Students)
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Students survey on "Hardest Topics"',
is3D: 'true'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var value = data.getValue(selectedItem.row, selectedItem.column);
alert('The user selected ' + value);
}
}
google.visualiation.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
Here's my code for PHP that connects to mySQL and populate my charts with its data
//MySQL query start
$sql="SELECT *
FROM googlechart";
//MySQL query end
//Result start
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
//Result end
//Rows start
$rows = array();
//Rows end
$flag = true;
//Table start
$table = array();
//Table end
//Table Column array start
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Weekly Task', 'type' => 'string'),
array('label' => 'Percentage', 'type' => 'number')
);
//Table Column array end
//Table Row array start
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['weekly_task']);
// Values of each slice
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
//Table Row array end
//Table Row start
$table['rows'] = $rows;
//Table Row end
//json start
$jsonTable = json_encode($table);
//echo $jsonTable;
//json end
?>
I have a Bar Chart that is very similar to my Pie Chart, but without addListener and selectHandler function, and it's showing properly.