'Chart.js error Cannot read property 'length' of null
I am using Chart.js
via an ajax call
$.ajax({
url: 'MenuG.aspx/GetGraphData',
type: "POST",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: loadChart,
error: function (xhr, status, error) {
alert("קרתה שגיאה בטעינת הגרף");
}
});
function loadChart(jsonData) {
var data = jsonData.d;
if (data != undefined && data != null) {
if (data.Col1 != null && data.Col2 != null && data.Col3 != null && data.Col4 != null) {
var labelsToDisplay = [data.Col1.Desc, data.Col2.Desc, data.Col3.Desc, data.Col4.Desc];
var dataTotal = [parseInt(data.Col1.total), parseInt(data.Col2.total), parseInt(data.Col3.total), parseInt(data.Col4.total)];
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: labelsToDisplay,
datasets: [
{
//label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9"],
data: dataTotal
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: jsonData.GraphName
},
animation: { // show each column total on top
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.fillStyle = "black";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
for (var key in dataset._meta) {
var model = dataset._meta[key].data[i]._model;
ctx.fillText(dataset.data[i], model.x, model.y - 5);
}
}
});
}
}
}
}); //Chart
}//if
}// if
} //loadChart
I created 2 arrays labelsToDisplay
is for the bars labels and dataTotal
for the bars values (I checked and they both have 4 values in it).
however, I get:-
Uncaught TypeError: Cannot read property 'length' of null
Uncaught TypeError: Cannot read property 'length' of null
at Object.acquireContext (Chart.min.js:13)
at t.construct (Chart.min.js:11)
at new t (Chart.min.js:12)
at Object.loadChart [as success] (MenuG.aspx?param=1:66)
at j (jquery.js:3148)
at Object.fireWith [as resolveWith] (jquery.js:3260)
at x (jquery.js:9314)
at XMLHttpRequest.b (jquery.js:9718)
Solution 1:[1]
I was using a cdn for Chart.js library, and when downloading the library and putting it in my project it solved the problem somehow...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | itay312 |