What I'm trying to do is use chartjs to create a Bar chart. The data is retrieved via $.ajax. And JSON data retrieved from $.ajax will be added later to dataset. However, when I'm about to create a chartjs. There is an error from Chart.js library:
Uncaught TypeError: Cannot read property '0' of undefined
I have checked all the data after finished loading the ajax .There is no problem with the JSON (I've already check the console). Moreover, when I checked the myBarChart
type is reported as undefined. Even I already assigned a new chartjs to itself after I finished retrive JSON data.
Here is a JavaScript Code:
var driverCode, driverPointsGained = "";
var exLabel = new Array();
var exPoints = new Array();
var chartData;
var myBarChart;
var ctx = document.getElementById("driverStandingChart").getContext("2d");
//var ctx = $("#driverStandingChart").get(0).getContext("2d");
Chart.defaults.global.responsive = true;
function addChartData(codename, pointsgained) {
chartData = {
label: codename,
datasets: [
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: pointsgained
}
]
};
return chartData;
}
$("#testAjaxLoading").click(function (e) {
e.preventDefault();
$.ajax({
url: "http://ergast.com/api/f1/current/driverStandings.json",
dataType: "json",
success: function (data) {
console.info(data);
for (var i = 0; i <= data.MRData.total-1; i++) {
driverCode = data.MRData.StandingsTable.StandingsLists[0].DriverStandings[i].Driver.code;
driverPointsGained = data.MRData.StandingsTable.StandingsLists[0].DriverStandings[i].points;
console.info("code: " + driverCode + " points: " + driverPointsGained);
//push data to array
exLabel.push(driverCode);
exPoints.push(driverPointsGained);
}
addChartData(exLabel,exPoints);
console.log(chartData);
myBarChart = new Chart(ctx).Bar(chartData);
alert("finished retrieve data");
},
error: function (err) {
console.error(err);
}
});
});
Full code with HTML: https://gist.github.com/sancowinx/31b6289b7f28908db0c1
For the JSON data, I use an API from Ergast API to get a JSON Results.
edit: adding Stack Trace:
$.ajax.success is actually
myBarChart = new Chart(ctx).Bar(chartData);
Any suggestions? Thanks in advance.
Your stack trace tells me that either ctx
or chartData
is undefined. My guess is that it's ctx
if you've already checked chartData. (Verify this using console.log
.) Perhaps this is the answer if that's the case: canvas.getContext("2d") is undefined
If that's not the case, then an element that ChartJS was looking for in your JSON was undefined. You'll have to look through the documentation to see what element is missing if that's the case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.