How can I display two lines in a Chart.js line chart using data from a JSON file with 2 objects stored in the database?
When attempting to show both sets of data simultaneously, I encountered an issue where the output was always undefined. Why is this happening and how can I fix it?
Error:
Cannot read property 'current_week' of undefined
JSON Output:
{"current":[{"current_week":23},{"current_week":636},{"current_week":237}],"last":[{"last_week":235},{"last_week":74},{"last_week":737},{"last_week":767},{"last_week":546},{"last_week":73},{"last_week":453}]}
JS Chart.js Code:
$(document).ready(function() {
$.ajax({
url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
type : "GET",
success : function(data) {
console.log(data);
var current_week = [];
var last_week = [];
for(var i in data) {
current_week.push(data.current[i].current_week);
last_week.push(data.last[i].last_week);
}
console.log(current_week);
console.log(last_week);
var visitorsChart = {
labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
datasets: [{
type : 'line',
data : current_week,
backgroundColor : 'transparent',
borderColor : '#007bff',
pointBorderColor : '#007bff',
pointBackgroundColor: '#007bff',
fill : false
},
{
type : 'line',
data : last_week,
backgroundColor : 'tansparent',
borderColor : '#ced4da',
pointBorderColor : '#ced4da',
pointBackgroundColor: '#ced4da',
fill : false
}]
};
var ctx = $("#visitors-chart");
var LineGraph = new Chart(ctx, {
data: visitorsChart,
});
},
});
});