Update Chart.js data with ajax

Viewed 451

I want to update my chart with ajax and Flask but I can not update the data:



  var chart = new Chart(canvas, {
    type: "line",
    datasets: [{
      label: 'My Dataset',
    }]

  })

  $(document).ready(function () {
    $.ajax({
      dataType: "text",
      contentType: "application/json",
      url: '{{ url_for("data_page") }}',
      type: "post",
      data: JSON.stringify({
        timeDelta: "7",
        technologie: "Java",
      }),
      success: function (data) {
        let json = $.parseJSON(data);  ==> [["2021-06-04", "2021-06-05"],[47, 3]]
        chart.data.labels.push(json[0]); ==> It seems to work

        chart.data.datasets[0].data = json[1]; ==> here I get : "Cannot set property 'data' of undefined"
        chart.update();
      }
    });
   });

I don't understand , where am I wrong ?

Thanks for any help !

1 Answers

It doesn't work because you initially create the chart with wrong configuration. The labels and datasets arrays must be contained in a data object.

Try this instead:

var chart = new Chart(canvas, {
  type: 'line',
  data: { 
    labels: [],
    datasets: [{
      label: 'My Dataset',
      data: [] 
    }]
  }
});
Related