I am completely new to using ChartJS and JavaScript, as I attempt to create some charts for my django application. I'm facing an issue while trying to generate multiple charts from distinct JSON objects within the same line. Currently, the same chart is being generated, which switches to the second view upon hovering. What I desire is one chart reflecting the first view or initial JSON object, and another chart displaying the second view/second JSON object. Take a look at my code snippet along with some sample data below:
data = [{'title': 'team', 'labels': ['Team score'], 'default': [50.0], 'title': 'single': 'labels': ['Single score'], 'default': [37.5]}]
JS:
var defaultData = [];
var labels = [];
function loadDashboard() {
$.ajax({
method: "GET",
url: endpoint,
success: function(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
var objName = Object.keys(data)[0];
var val = data[key];
labels = val.labels;
defaultData = val.default;
updateChart(label=labels, data=defaultData, elementId=objName)
}
}
},
error: function(error_data) {
console.log("error");
console.log(error_data)
}
});
}
function updateChart(label, data, elementId) {
var tableName = document.getElementById(elementId).getContext('2d');
var elementId = new Chart(tableName, {
type: 'bar',
data: {
labels: label,
datasets: [{
label: 'NPS Score',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
$(document).ready(function() {
loadDashboard()
});
HTML
<div class="row">
<div class="col-sm-6" id="teamScore" url-endpoint="{% url 'nps-dashboard-data' %}">
<canvas id="teamScoreChart" width="400" height="400"></canvas>
</div>
<div class="col-sm-6" id="singleScore">
<canvas id="singeScoreChart" width="400" height="400"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="{% static 'js/dashboard.js' %}"></script>
</div>