Chart Js , loading data on selection but bar graph displaying old values as well on hovering

天大地大妈咪最大 提交于 2021-01-29 08:56:05

问题


I am trying to dynamically update the chart. I have got different values from the database via another js for name (#cellname) also there is cellname and throughput against each other in data.php (which is being called by ajax).

Whenever new selection is made the below script is running fine except when i move mouse on the graph it displays old graph as well, somehow i am lacking to use the chart update function.

$(document).ready(function() {
  function load_stats(id) {
    $.ajax({
      url: "http://localhost/visx/data.php",
      method: "GET",
      data: {
        id: id
      },
      dataType: "JSON",
      success: function(data) {
        console.log(data);

        // variable declaration
        var date = [];
        var cellname = [];
        var throughputs = [];

        // Store database values to Variables
        for (var i in data) {
          date.push(data[i].starttime);
          cellname.push(data[i].cellname);
          throughputs.push(data[i].thrp_bits_dl);    
        }

        // Creating Chart
        var ctx = document.getElementById('VF_Requests').getContext('2d');
        var chart = new Chart(ctx, {
          type: 'bar',
          data: {
            labels: date,
            datasets: [{
              // label:,
              backgroundColor: 'rgb(174,199,232)',
              data: throughputs,
            }]
          },
        });
      },
    });
  }

  // load function
  $('#cellname').click(function() {
    var id = $('#cellname option:selected').val();
    if (id != '') {
      load_stats(id);
    } else {

    }
  });
});

回答1:


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

To do so, you'll define a global variable chart and change your code as follows:

var chart;
function load_stats(id) {
  $.ajax({
      ...

      if (chart) {
        // Updating Chart
        chart.data.labels = date;
        chart.data.datasets[0].data = throughputs;  
        chart.update();
      } else {
        // Creating Chart
        chart = new Chart('VF_Requests', {
          type: 'bar',
          data: {
            labels: date,
            datasets: [{
              backgroundColor: 'rgb(174,199,232)',
              data: throughputs
            }]
          }
        });
      }
    },
  });
}


来源:https://stackoverflow.com/questions/61573166/chart-js-loading-data-on-selection-but-bar-graph-displaying-old-values-as-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!