2016-04-15 16 views
12

Utilizzo di Chart js Sto tentando di estrarre dati dalla chiamata Ajax per fornire al grafico. Ho trovato alcuni altri post in cui le persone hanno suggerito di ritardare il caricamento della tela ma nulla è sembrato funzionare. Attualmente questo è il quello che ho qui sotto e l'errore che ottengo èGrafico Js Impossibile leggere la proprietà 'length' di undefined

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); 


     } 
    }); 
    } 
}); 

aggiornamento qui che mostra come NON AJAX FUNZIONA

Il codice qui sotto sta prendendo i risultati del Ajax ottenere la richiesta (che ho ottenuto scaricandola nella console) e creando una versione "hard coded" della stessa cosa. L'unica cosa che dovrebbe essere tecnicamente diversa è che uno ha i dati caricati al momento della pagina e il secondo i dati vengono caricati molto brevemente dopo.

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); 

Aggiornamento ho cambiato dalla versione min di chart.js alla versione completa così ho potuto vedere dove esattamente è stato erroring fuori a.

Ecco l'immagine dal console cromata enter image description here

+0

Si dovrebbe convalidare che stai ricevendo i dati in un formato che ci si aspetta da questa chiamata AJAX. Ho intenzione di assumere dopo aver esaminato l'errore, Chart.js non sta ricevendo alcun dato in qualche modo (o è formattato in modo errato). –

+0

Non dovresti sostituire 'dataset' con' barChartData'? – christiandev

+0

Quindi dovrei averlo aggiunto alla domanda.Ho scaricato i dati nella console in modo da poterli visualizzare. Ho quindi copiato tali dati e creato una variabile dummy per esso e ho assegnato quella var al grafico. I dati sono così codificati e funzionano, quindi posso solo presumere che abbia qualcosa a che fare con la stessa chiamata ajax – scripter78

risposta

5

trovato la risposta,

I risultati Ajax deve essere analizzato prima.

conseguente correzione

var barChartData = JSON.parse(d); 
0

Sembra che si sta utilizzando un oggetto che non esiste, beh almeno io posso vedere che, datasets. Posso vedere solo length chiamato su questo oggetto, a meno che non ci sia del codice mancante?

posso vedere si assegna d a barChartData

var barChartData = d; 

Quindi, si potrebbe desiderare di sostituire le istanze di datasets con barChartData.

1

maggiori spiegazioni e gli altri utenti che ha questo problema, assicurarsi che il proprio elemento contenitore tela è esiste

5

Il problema è che quando il codice viene eseguito, la tela non è stato creato ancora. Dovresti inserire il codice in una funzione e assegnarla a window.onload event. Puoi vedere il codice di esempio qui sotto.

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>

0

eseguendo i seguenti ha lavorato per me:

window.onload = function() { 

} 
Problemi correlati