我想将数据库中的数据显示到图表Morris.js中。我需要从我的下拉列表中选择一个分支,当我选择一个分支时,该分支的总销售额应该转移到Morris.js条形图。我在将数据传输到条形图时遇到问题。我正在使用AJAX,PHP和Morris.js。
下拉列表的PHP代码:
<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>
用于图表显示的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_data);
}
});
});
fetch_yearly_sales.php的PHP代码:
<?php
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST["branch"]);
$ar = array();
if(!empty($data)){
$sql = "SELECT 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)) {
$ar[] = array(
'year' => $row['year'],
'sales' => $row['sales']
);
}
echo json_encode($ar);
}
else if (empty($data)){
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$ar[] = array(
'year' => $row['year'],
'sales' => $row['sales']
);
}
echo json_encode($ar);
}
答案 0 :(得分:0)
您没有指定您遇到的问题,但是从代码中看起来您将JSON字符串传递给Morris,而实际上它需要一个JSON对象。因此,请尝试将data: branch_data
更改为data: JSON.parse(branch_data)
。我可能是错的,如果你指明了什么不起作用会有所帮助。
答案 1 :(得分:0)
我想您需要使用函数 setData(),而不是始终创建新图表。这将使用参数中给出的数据更新图表。你需要改成这样的东西:
var branch_data = [];
var my_chart = new Morris.Bar({
element: 't-yearly-sales',
data: branch_data,
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
dataType: "json",
success: function(branch_data){
my_chart.setData(branch_data);
}
});
});
顺便说一下,我在上面的代码中提到了dataType到JSON,这样你就不需要从服务器解析结果了。