I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of charts when selected. Anyone able to provide some assistance? Thanks!
<body>
<div class="chartMenu">
<p>Loan Applications Accepted</p>
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
<button onclick="(new getChart()).back();"> GO BACK </button>
<select onchange="(new start()).changeChart();">
<optgroup label="Select Chart"></optgroup>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="line">Line</option>
<option value="doughnut">Doughnut</option>
</select>
function fetchData(url) { $.ajax({ url: url, type: "GET",
success: function (data) {
coordinates = [];
Array.from(data).forEach(element => {
coordinates.push({ x: element.x_axis, y: element.y_axis })
});
getChart();
},
error: function (error) {
console.log(`Error ${error}`);
}
});
};
function getChart() {
var data = {
datasets: [{
label: 'No of Loan Applications',
data: coordinates,
backgroundColor: [
'rgba(193, 32, 32, 0.58)',
'rgba(75, 192, 192, 0.58)',
'rgba(255, 159, 64, 0.58)',
'rgba(153, 167, 64, 0.58)',
'rgba(153, 102, 255, 0.58)',
],
borderColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(255, 159, 64, 1)',
],
borderWidth: 1
}]
};
var config = {
type: 'bar',
data,
options: {
scales: {
y: {
},
},
}
};
var ctx = document.getElementById('myChart');
let myChart = new Chart(
ctx,
config
);
this.back = function () {
if (myChart != null) {
myChart.destroy();
}
fetchData('http://localhost:8080/jsonGet?year=1')
myChart.data.datasets[0].data = coordinates;
myChart.update();
};
function clickHandler(click) {
const points = myChart.getElementsAtEventForMode(click, 'nearest', { intersect: true }, true);
if (points.length) {
const firstPoint = points[0];
if (firstPoint.element.$context.raw.x == "2020") {
fetchData('http://localhost:8080/jsonGet?year=2020')
myChart.data.datasets[0].data = coordinates;
myChart.update();
}
else if (firstPoint.element.$context.raw.x == "2021") {
fetchData('http://localhost:8080/jsonGet?year=2021')
myChart.data.datasets[0].data = coordinates;
myChart.update();
}
else if (firstPoint.element.$context.raw.x == "2022") {
fetchData('http://localhost:8080/jsonGet?year=2022')
myChart.data.datasets[0].data = coordinates;
myChart.update();
}
else {
console.log("Wrong input");
}
}
};
ctx.onclick = clickHandler;
function changeChart(chartType) {
console.log(chartType);
console.log(chartType.value);
}
function start() {
getChart();
clickHandler(click);
changeChart(chartType)
}
start();
};
$(document).ready(fetchData(url));