Chart Js Cannot read property 'length' of undefined

时间:2016-04-15 14:53:20

标签: javascript jquery chart.js

Using Chart js I am trying to pull data from Ajax call to supply to the Chart. I found a few other postings where people have suggested delaying the canvas load but nothing has seemed to work. Currently this is the what I have below and the error that I get is

enter image description here

$(function () {

GetChartData();

    function GetChartData() {
    $.ajax({
        url: ajaxURL,
        method: 'GET',
        dataType: 'json',
        success: function (d) {
            //-------------
            //- BAR CHART -
            //-------------
            var barChartData = d;
            var barChartCanvas = $("#barChart").get(0).getContext("2d");
            var barChart = new Chart(barChartCanvas);
            // console.log(datajson);
            //barChartData.datasets[1].fillColor = "#00a65a";
            //barChartData.datasets[1].strokeColor = "#00a65a";
            //barChartData.datasets[1].pointColor = "#00a65a";
            var barChartOptions = {
                //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
                //scaleBeginAtZero: true,
                //Boolean - Whether grid lines are shown across the chart
                scaleShowGridLines: true,
                //String - Colour of the grid lines
                scaleGridLineColor: "rgba(0,0,0,.05)",
                //Number - Width of the grid lines
                scaleGridLineWidth: 1,
                //Boolean - Whether to show horizontal lines (except X axis)
                scaleShowHorizontalLines: true,
                //Boolean - Whether to show vertical lines (except Y axis)
                scaleShowVerticalLines: true,
                //Boolean - If there is a stroke on each bar
                barShowStroke: true,
                //Number - Pixel width of the bar stroke
                barStrokeWidth: 2,
                //Number - Spacing between each of the X value sets
                barValueSpacing: 5,
                //Number - Spacing between data sets within X values
                barDatasetSpacing: 1,
                multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>",
                //String - A legend template
                legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
                //Boolean - whether to make the chart responsive
                responsive: true,
                maintainAspectRatio: true
            };


            barChartOptions.datasetFill = false;
            barChart.Bar(barChartData, barChartOptions);


        }
    });
    }
});

UPDATE HERE SHOWING HOW NON AJAX WORKS

The below code is taking the results of the Ajax get request (which I got from dumping it to the console) and creating a "hard coded" version of the same thing. The only thing that should technically be different is one has the data loaded at time of the page and the second the data is loaded very briefly after.

 var chartData = {
    "labels": [
      "April"
    ],
    "datasets": [
      {
          "label": "Not Sure What to Put Here",
          "fillColor": "#662B60",
          "strokeColor": "#662B60",
          "pointColor": "#662B60",
          "pointStrokeColor": "#662B60",
          "pointHighlightFill": "#662B60",
          "pointHighlightStroke": "#662B60",
          "data": [
            1
          ]
      },
      {
          "label": "Not Sure What to Put Here",
          "fillColor": "#88B56E",
          "strokeColor": "#88B56E",
          "pointColor": "#88B56E",
          "pointStrokeColor": "#88B56E",
          "pointHighlightFill": "#88B56E",
          "pointHighlightStroke": "#88B56E",
          "data": [
            1
          ]
      },
      {
          "label": "Not Sure What to Put Here",
          "fillColor": "#48CA2B",
          "strokeColor": "#48CA2B",
          "pointColor": "#48CA2B",
          "pointStrokeColor": "#48CA2B",
          "pointHighlightFill": "#48CA2B",
          "pointHighlightStroke": "#48CA2B",
          "data": [
            0.83
          ]
      }
    ]
};


    //-------------
    //- BAR CHART -
    //-------------
var barChartData = chartData;
    var barChartCanvas = $("#barChart").get(0).getContext("2d");
    var barChart = new Chart(barChartCanvas);

    //barChartData.datasets[1].fillColor = "#00a65a";
    //barChartData.datasets[1].strokeColor = "#00a65a";
    //barChartData.datasets[1].pointColor = "#00a65a";
    var barChartOptions = {
        //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
        //scaleBeginAtZero: true,
        //Boolean - Whether grid lines are shown across the chart
        scaleShowGridLines: true,
        //String - Colour of the grid lines
        scaleGridLineColor: "rgba(0,0,0,.05)",
        //Number - Width of the grid lines
        scaleGridLineWidth: 1,
        //Boolean - Whether to show horizontal lines (except X axis)
        scaleShowHorizontalLines: true,
        //Boolean - Whether to show vertical lines (except Y axis)
        scaleShowVerticalLines: true,
        //Boolean - If there is a stroke on each bar
        barShowStroke: true,
        //Number - Pixel width of the bar stroke
        barStrokeWidth: 2,
        //Number - Spacing between each of the X value sets
        barValueSpacing: 5,
        //Number - Spacing between data sets within X values
        barDatasetSpacing: 1,
        multiTooltipTemplate: "<%=datasetLabel%>: <%= value + ' %' %>",
        //String - A legend template
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
        //Boolean - whether to make the chart responsive
        responsive: true,
        maintainAspectRatio: true
    };


    barChartOptions.datasetFill = false;
    barChart.Bar(barChartData, barChartOptions);

Update I changed from the min version of chart.js to the full version so I could see where exactly it was erroring out at.

Here is the image from chrome console enter image description here

7 个答案:

答案 0 :(得分:7)

问题在于,当您的代码执行时,尚未创建画布。 您应该将代码包装在函数中,并将该函数分配给window.onload事件。您可以在下面看到示例代码。

window.onload = function() {
  var ctx = document.getElementById("myChart");
  var lineChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
      datasets: [{
        label: "2015",
        data: [10, 8, 6, 5, 12, 8, 16, 17, 6, 7, 6, 10]
      }]
    }
  })
}
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>

</head>

<body>
  <canvas id="myChart"></canvas>
</body>

</html>

答案 1 :(得分:5)

找到答案,

必须首先解析Ajax结果。

结果修复

var barChartData = JSON.parse(d);

答案 2 :(得分:1)

有更多解释和有此问题的其他用户,请确保您的容器画布元素存在

答案 3 :(得分:1)

您可以尝试将Chart.JS脚本标记和其他自定义JS脚本放在**<**/body>标记的末尾。

答案 4 :(得分:0)

It looks like you're using an object that doesn't exist, well at least I cant see it, datasets. I can only see length being called on this object, unless there's missing code?

I can see you assign d to barChartData

var barChartData = d;

So, you might want to replace the instances of datasets with barChartData.

答案 5 :(得分:0)

运行以下内容对我有用:

window.onload = function () {

}

答案 6 :(得分:0)

这是一个老问题,但是,我也有这个问题,在我的情况下,我的数据长度 = 0。我解决了这个问题,只是在调用图表之前添加了验证:

if (barChartData.length > 0)
{
   objChart = Morris.Bar({....
}