Search code examples
jqueryjsonchart.js

Unable to put JSON data into Chart.JS


I'm new to Chart.js, and am trying to display a bar chart, with data called using jquery's AJAX call to a PHP file contains mysql query where the data are stored.

The page where the chart is supposedly displayed, only displayed the X and Y axis, but no chart is displayed, even though the array I got from Ajax call is present.

HTML Page

<!DOCTYPE html>
<html>
<head>
  <title>Chart.js Sample</title>
  <script type="text/javascript" src="chart.umd.js"></script>
  <script type="text/javascript" src="jquery-3.6.0.min.js"></script>
  <style type="text/css">
    #myChart {
      min-width: 100px;
      max-width: 500px;
      min-height: 200px;
      max-height: 400px;
    }
  </style>
</head>
<body>
  <canvas id="myChart"></canvas>

  <script type="text/javascript">
    var chData = [];

    $(document).ready(function(){

      $.ajax({
        url: "ajax.php",
        method: "GET",
        dataType: "JSON",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
          chData = data;
        }
      });

      var chartId = new Chart($("#myChart"), {
         type: 'bar',
         data: {
            labels: ["HTML", "CSS", "JAVASCRIPT", "CHART.JS", "JQUERY"],
            datasets: [{
               label: "Subjects",
               data: chData
            }]
         }
      });

    });
  </script>
</body>
</html>

AJAX Page:

<?php

$conn = mysqli_connect("localhost", "root", "mypass", "chart") or die("Mysql Error Connect: ".mysqli_error());

  $arr = [];

  $q = mysqli_query($conn, "SELECT score FROM score");
  if(mysqli_num_rows($q)>0) {
    while($x = mysqli_fetch_array($q)) {
      $score = $x["score"];
      array_push($arr, $score);
    }
  }
  
  header('Content-type: application/json');
  echo json_encode($arr);

?>

If you run the code and open the console in the developer options, you'd find the JSON array is already there:

chData
(5) ['44', '35', '22', '28', '73']

Solution

  • The AJAX request is asynchronous. From your current code, it will proceed to the var chartId = ... line without waiting for the request to be completed.

    Hence, you should move the part to create the Chart instance to the success callback so that when the response is returned with the success status code, it will pass the data to create the Chart instance.

    $.ajax({
      url: "ajax.php",
      method: "GET",
      dataType: "JSON",
      contentType: "application/json; charset=utf-8",
      success: function(data) {
        var chartId = new Chart($("#myChart"), {
          type: 'bar',
          data: {
            labels: ["HTML", "CSS", "JAVASCRIPT", "CHART.JS", "JQUERY"],
            datasets: [{
              label: "Subjects",
              data: data
            }]
          }
        });
      }
    });
    

    And you don't need to declare the global variable for chData.