如何从ajax调用更新数据(chart.js)



我设法从来自php文件的ajax调用生成图形。我想通过下拉列表从客户字段(chg_customer)的选择中修改这个图形。我的下拉列表可以工作并显示客户的名称。但是,我无法从这个选择中生成一个新的图表,其中包含与正确客户对应的正确数字(计数)。你能帮我吗?谢谢你

html:

<select id="filter"> 
<option>Tous</option>
</select> 
<canvas id="graph4Canvas" style="height: 700px; width: 100%;"></canvas></select>

graph.js:

$(document).ready(function() {
$.ajax({
url: 'graph4.php',
type: 'GET',
dataType: 'json',
success: function(data) {
var chg_customer = [];
var count = [];
for (var i in data) {
chg_customer.push(data[i].chg_customer);
count.push(data[i].count);
}
var ctx = $('#graph4Canvas');
const barGraph = new Chart(document.getElementById('graph4Canvas'), {
type: 'bar',
data: {
labels: data.map(o => o.chg_customer),
datasets: [{
label: 'Clients',
data: data.map(o => o.count),
backgroundColor: "rgba(0, 0, 255, 0.5)",
yAxisID: 'Nombres',
xAxisID: 'Clients',
}]
},
options: {
scales: {
yAxes: [{
id: "Nombres",
ticks: {
beginAtZero: true,
stepSize: 1,
fontSize: 15,
},
scaleLabel: {
display: true,
labelString: 'Nombres'
},
gridLines: {
drawOnChartArea: false
},
}],
xAxes: [{
id: "Clients",
ticks: {
beginAtZero: true,
stepSize: 1,
fontSize: 10,
},
scaleLabel: {
display: false,
},
gridLines: {
drawOnChartArea: false
},
}],
},
title: {
display: false,
},
legend: {
display: false,
},
},
});

data.forEach(o => {
const opt = document.createElement('option');
opt.value = o.chg_customer;
opt.appendChild(document.createTextNode(o.chg_customer));
document.getElementById('filter').appendChild(opt);
});

$("#filter").change(function() {
//update data 
});

不需要生成新的图表。一旦图表存在,您需要做的就是编辑数据集并调用图表更新函数来重新呈现图表。

e。G(示例在我的情况下使用angular,但仍然应该应用):

HTML:

<mat-select [(value)]="selectedFilter" (selectionChange)="filterStreamType()">

JS:

public filterStreamType() {
// code manipulates data....
this.chart.data.datasets = newData; // update our dataset so chart js can re-draw it   
this.chart.update(); // This is a redundant call but I did a bad job here and mixed some things that should not be mixed and so
}

还请注意,在V2和V3之间有一些突破性的变化,因此该语法可能会根据您使用的版本而有所不同。

最新更新