[Chartjs]-Chartjs Data via json request not populating

3👍

Assuming that you want to populate the response of AJAX Call in offences variable.
There are 2 issues with your current code:

  1. Your code to create chart is running before the AJAX Call has run. In your code you are referencing offences variable but it is not yet populated.

  2. You have defined offences as a global Variable, which is ok. But inside the AJAX Call you are again defining a new Local Variable offences by prefixing it with var. You need to use the below code which is commented in your question to populate the Global offences var.

    offences = result

One way of fixing this would be to encompass your Chart Code in a New Function and inside the success callback of AJAX, call this New Function.

//Global Variable
var offences = [];

function createMonthAbuseChart() {
    var ctx = document.getElementById("monthAbuseChart");
    var myLineChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ["1", "2", "3"],
          datasets: [{
            label: "Offences",
            //data: [0, 7, 5] This works
            data: offences // This doesn't
        }],
      }
      }
    });
}

// Grab the data for offences:
$.ajax({
  method: "POST",
  url: "sql/monthabuse.php",
  dataType : 'json',
  success: function (result) {
      offences = result;
      console.log(result);
      createMonthAbuseChart(); //Call the Chart Create Method Here.
  },
});

You must make sure that data returned by AJAX Call has the same format as the data required for chart which is [0, 7, 5]. From your question it looks your AJAX Call is returning {19: 4, 05: 4, 09: 4}. You can use the following code to convert it into [4, 4, 4]

    offences = Object.values(result);

Use the above line instead of following in your AJAX Callback

    offences = result;

Leave a comment