I utilized AJAX to dynamically render the chart. There are two main files involved: index.php and selectchart.php. The index.php file contains the AJAX code to render the chart.
<div class="chart-area">
<div id="chart-1"><!-- Fusion Charts will render here--></div>
<div id="chart-mon"><!-- Fusion Charts will render here--></div>
The div with ID chart-1 is used for displaying the annual report, while the chart displayed changes based on the selected month.
</div>
<p><select class="btn btn-light btn-icon-split" id="country" name="country">
<option>--Select Month--</option>
<option value="01">JAN</option>
<option value="02">FEB</option>
<option value="03">MAR</option>
<option value="04">APR</option>
<option value="05">MAY</option>
...
</select></p>
Javascript
<script type="text/javascript">
$('#country').change(function() {
var selectedCountry = $(this).children("option:selected").val();
$.ajax({
type : "POST",
url : "selectchart.php?country="+selectedCountry,
data : selectedCountry,
success: function(result) {
$("#chart-1").hide();
alert(result);
var myChart = new FusionCharts("column2D", "myThird", 400, 300, "json", result);
myChart.render("chart-mon");
}
});
});
</script>
When testing, the alert showed [objectoject]
, but no data was displayed in chart-mon
.
Content of selectchart.php:
include("includes/fusioncharts.php");
$selectData = $_REQUEST['country'];
$dbHandle = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if ($dbHandle->connect_error) {
exit("Connection error: ".$dbHandle->connect_error);
}
$strQueryMon = "SELECT name, amount FROM income WHERE month = '$selectData' ORDER BY amount DESC LIMIT 10";
$resultMon = $dbHandle->query($strQueryMon) or exit("Error code ({$dbHandle->errno}): {$dbHandle->error}");
if ($resultMon) {
$arrDataMon = array(
"chart" => array(
"showValues" => "0",
"theme" => "zune"
)
);
$arrDataMon["data"] = array();
while($rowMon = mysqli_fetch_array($resultMon)) {
array_push($arrDataMon["data"], array(
"label" => $rowMon["name"],
"value" => $rowMon["amount"]
));
}
$jsonEncodedDataMon = json_encode($arrDataMon);
echo $jsonEncodedDataMon;
header('Content-type: text/json');
}