0👍
✅
The problem is that all your charts use the same array
for labels
and also the same array
for datasets.data
. Each time, the chartAjax
function is invoked, their content is overwritten.
To make this work, you could rewrite your code as follows. Providing the specific chart creation function as a parameter to the function chartAjax
. When the ajax call is successful, chartAjax
would then invokes the chart creation function with the correct data each.
async function chartAjax(url, interval, chartCreationFunction) {
$.ajax({
async: false,
url: url,
method: "GET",
dataType: "json",
data: {
'interval': interval,
},
success: function(response) {
let resChart = JSON.parse(JSON.stringify(response));
let chartLabels = resChart.data.map(o => o['date']);
let chartData = resChart.data.map(o => o['count']);
chartCreationFunction(chartLabels, chartData);
},
});
}
function createOrderChart(chartLabels, chartData) {
var myLineChart = new Chart(document.getElementById("orderChart"), {
type: 'line',
data: {
labels: chartLabels,
datasets: [{
label: "Orders",
data: chartData,
backgroundColor: [
"rgba(140, 184, 179, .2)",
],
borderColor: [
"rgba(214, 255, 250)",
],
borderWidth: 2
}, ]
},
options: {
responsive: true
}
});
}
function createTradeChart(chartLabels, chartData) {
var myLineChart1 = new Chart(document.getElementById("tradeChart"), {
type: 'line',
data: {
labels: chartLabels,
datasets: [{
label: "Trades",
data: chartData,
backgroundColor: [
"rgba(219, 255, 251, .2)",
],
borderColor: [
"rgba(219, 255, 251)",
],
borderWidth: 2
}, ]
},
options: {
responsive: true
}
});
}
function createUserChart(chartLabels, chartData) {
var myLineChart2 = new Chart(document.getElementById("usersChart"), {
type: 'line',
data: {
labels: chartLabels,
datasets: [{
label: "Users",
data: chartData,
backgroundColor: [
"rgba(224, 255, 251, .2)",
],
borderColor: [
"rgba(224, 255, 251)",
],
borderWidth: 2
}, ]
},
options: {
responsive: true
}
});
}
chartAjax("/api/v1/admin/orderCahrt", 'm', createOrderChart);
chartAjax("/api/v1/admin/tradeChart", 'm', createTradeChart);
chartAjax("/api/v1/admin/userChart", 'm', createUserChart);
Source:stackexchange.com