Chartjs-Update chart in chart js without reloading the page

2👍

The problem is that the myChart variable is declared inside the scope of the AJAX success function. The variable only exists within the function body during its execution. When the user performs a new search, the success function is invoked again but the initially created myChart variable does no longer exist.

You can solve your problem by creating myChart at the beginning in the global scope as follows.

var myChart = new Chart('myChart', {
  type: "bar",
  data: {
    labels: [], // initialize with an empty array
    datasets: [{
      label: "# of Votes",
      data: [], // initialize with an empty array
      ...
});

Your event listener and AJAX request would then look as shown below. Note that I set the labels and data on the existing chart and call myChart.update() afterwards. This is cleanest and the most efficient way to deal with new data. For further details, please consult Updating Charts from chart.js documentation.

var endpoint = "/api/chart/data";
myform.addEventListener("submit", function(e) {
  e.preventDefault();
  var name = document.querySelector("#name").value;
  var amount = document.querySelector("#amount").value;
  $.ajax({
    method: "GET",
    url: endpoint + "?name=" + name + "&amount=" + amount,
    success: function(data) {
      myChart.data.labels = data.labels;
      myChart.data.datasets[0].data = data.data;
      myChart.update();
    },
    error: function() {
      console.error('enter valid data')
    }
  });
});

Leave a comment