Chartjs-Unable to load Chart.js data from getJSON / PHP?

0👍

var ctx = document.getElementById("myChart").getContext("2d");
let myChart = null;

function getConfig(chart_data){
  return ({
    type: "pie",
    data: {
      labels: ["Total", "Size X", "Size XS", "Size SM"],
      datasets: [
        {
          data: chart_data,
          backgroundColor: [
            "rgb(54,162,235)",
            "rgb(255,99,132)",
            "rgba(255, 159, 64, 1)",
            "rgb(255,192,33)"
          ],
          borderColor: [
            "rgb(255,255,255)",
            "rgb(255,255,255)",
            "rgb(255,255,255)",
            "rgb(255,255,255)"
          ],
          hoverBackgroundColor: ['#373739', '#373739', '#373739', '#373739'],
        }
      ]
    },
    options: {
      responsive: true,
      animation: {
        duration: 0, //2800, I remove animation time
        easing: "easeInOutQuad"
      },
      tooltips: {
        mode: 'nearest'
      },
      layout: {
        padding: {
          left: 0,
          right: 0,
          top: 15,
          bottom: 0
        }
      },
      cutoutPercentage: 66,
      legend: {
        display: false,
        position: "bottom",
        fullWidth: true
      }
    }
  });
}

function getJSON(){
    // emulate fetch
  return new Promise(resolve => {
    const chart_data = [
      Math.random() * 50,
      Math.random() * 50,
      Math.random() * 50,
      Math.random() * 50
    ];
    resolve(chart_data)
  })
}

function update(){
  getJSON().then(data => {
      myChart.data.datasets[0].data = data;
      myChart.update();
  });
}

function initializeChart() {
    getJSON().then(data => { 
        myChart = new Chart(ctx, getConfig(data));
    });
}

initializeChart();
document.getElementById('update_chart').addEventListener('click', update, false);
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  </head>
  <body>
    <div>
      <button id="update_chart">Update Records</button>
    </div>
    <canvas id="myChart" width="50" height="40"></canvas>
  </body>
</html>

0👍

Query.getJSON() makes an asynchronous HTTP request. Once the result arrives, the chart has already been created and the obtained data has no effect on the chart.

To solve this, place the chart creation inside the then callback as follows.

$.getJSON("chartdata.php").then(function(chart_data) {
  var ctx = document.getElementById('myChart');
  var myChart = new Chart(ctx, {
    type: 'pie',
    ...
});

Leave a comment