程序流程:
1.加载页面后,图表将显示所有分支的总销售额。
2.当您从下拉按钮中选择一个分支时,图表显示的数据就是该特定分支的总销售额。
我的问题是,当我单击特定分支时,数据根本不会显示。
请参阅屏幕截图和代码以获取更多信息。
屏幕截图:
Screenshot of the page when it loads
Screenshot of the page when I choose a branch
PHP数据代码:
<div class="report-header">
<h5 class="report-title">Total Yearly Sales</h5>
<div class="branch-report">
<select class="form-control" id="t-yearly">
<option value="">Branch</option>
<?php
require_once "connect.php";
$sql = "SELECT id,branch FROM tblLocation";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['id']."'>".$row['branch']."</option>";
}
?>
</select>
</div>
</div>
<div id="t-yearly-sales" style="height: 80%;"></div>
<?php
include "connect.php";
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
$chart = '';
while ($row = mysqli_fetch_array($result)){
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
?>
<script>
new Morris.Bar({
element: 't-yearly-sales',
data: [<?php echo $chart; ?>],
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
</script>
AJAX代码:
//Total Yearly Sales
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
success: function(branch_data){
new Morris.Bar({
element: 't-yearly-sales',
data: [branch_data],
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
console.log(branch);
}
});
});
Fetch_Yearly_Sales.php代码:
<?php
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST['branch']);
if($data == ""){
$output = "";
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
ob_clean();
echo $output;
}
else{
$output = "";
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
ob_clean();
echo $output;
}
?>
最佳答案
您可以在PHP中尝试
if($data == ""){
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$chart = '{year:'.$row["year"].', sales:'.$row["sales"].'},';
}
echo $chart;
} else {
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart = '{year:'.$row["year"].', sales:'.$row["sales"].'}';
}
echo $chart;
}
关于javascript - 使用AJAX PHP显示数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48879126/