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.