Chartjs-I'm trying to get data from flask app but I get this "Uncaught ReferenceError: _data is not defined"

3👍

You are declaring the _data variable in your $(document).onReady() function. That variable will be only available inside it. The code that tries to draw the chart is outside of that function so it cannot access the _data variable. Try moving the code that creates the chart inside of your success function so that you have the data available and can render the chart immediately.

$(document).ready(function() {
  var _data;
  var _labels;
  var myPieChart;

  $.ajax({
    url     : "/get_data",
    type    : "get",
    data    : {vals: ''},
    success : function(response) {
      full_data = JSON.parse(response.payload);
      _data     = full_data['data'];
      _labels   = full_data['labels'];

      // Pie Chart Example
      var ctx = document.getElementById("myPieChart");

      myPieChart = new Chart(ctx, {
        type : 'doughnut',
        data : {
          labels   : _labels,
          datasets : [{
            data                 : _data,
            backgroundColor      : ['#4e73df', '#1cc88a', '#36b9cc'],
            hoverBackgroundColor : ['#2e59d9', '#17a673', '#2c9faf'],
            hoverBorderColor     : "rgba(234, 236, 244, 1)",
          }]
        },
        options : {
          maintainAspectRatio : false,
          tooltips            : {
            backgroundColor : "rgb(255,255,255)",
            bodyFontColor   : "#858796",
            borderColor     : '#dddfeb',
            borderWidth     : 1,
            xPadding        : 15,
            yPadding        : 15,
            displayColors   : false,
            caretPadding    : 10
          },
          legend : {
            display : false
          },
          cutoutPercentage : 80
        }
      });
    }
  });
});

Leave a comment