Chartjs-Chart.js after ajax refresh there are two charts in the same container (new and old)

0👍

The problem is that the old chart is still present in the canvas when you create the new chart. Instead of creating a new chart each time new data is available, you should simply assign the new values to the existing chart configuration and then update the existing chart.

chartTHolder.data.datasets[0].data = chDataObj.dataListT; 
chartTHolder.options.scales.yAxes[0].ticks.min = chDataObj.dataChartBoudaries.minT;
chartTHolder.options.scales.yAxes[0].ticks.max = chDataObj.dataChartBoudaries.maxT;
chartTHolder.update();

Your code would have to be changed as follows. Note that chartTHolder is defined outside the function GenerateRuntimeGraph.

let chartTHolder = null;
function GenerateRuntimeGraph(id, days) {
  $.ajax({
    type: "POST",
    url: `/Devices/ChartData?id=${id}&days=${days}`,
    success: function(chData) {
      let chDataObj = JSON.parse(chData);
      if (chartTHolder) {
        chartTHolder.data.datasets[0].data = chDataObj.dataListT; 
        chartTHolder.options.scales.yAxes[0].ticks.min = chDataObj.dataChartBoudaries.minT;
        chartTHolder.options.scales.yAxes[0].ticks.max = chDataObj.dataChartBoudaries.maxT;
        chartTHolder.update();
      } else {    
        var options = { 
          ... 
        };
        var ctx = document.getElementById('myChartT').getContext('2d');
        chartTHolder = new Chart(ctx, options);
      }
    }
  });
}

Leave a comment