user1765369
user1765369

Reputation: 1405

Re-running chart.js with different variable

On page load my code generates a bar chart via AJAX request:

function docharts(name) {   
 $.ajax({
        url: "sql/getdata.php",
        method: "GET",
        data: {
            staff: name,
        },
        success: function(data) {

            **code to assign labels etc**

        var ctx = document.getElementById("summary").getContext("2d");
        var myChart = new Chart(ctx, {
                 showTooltips: true,
                type: 'bar',
                data: chartdata,            

                });
        myChart.update();        
        },
        error: function(data) {
            console.log(data);
        }
    }); 
};

This works as expected. However I want to be able to re-run this function with a different variable ("name") and for it to redraw the chart based on this new data.

When I run docharts("foobar") the graph does redraw with the new data, however when the cursor is dragged back outside the canvas it appears to redraw the original graph.

What am I doing wrong?

Upvotes: 2

Views: 245

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31421

If you instead of declaring the variable in your ajax request, declare it beforehand and check if there is an active chart and destroy that first then your behaviour will go away.

var chart = null;

const addChart = (chartConfig) => {
  if (chart) chart.destroy();

  var ctx = document.getElementById('chartJSContainer').getContext('2d');
  chart = new Chart(ctx, chartConfig);

  chart.update(); 
}

Working sample:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var options2 = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var chart = null; // DECLARE BEFOREHAND

var option1 = true;

const addChart = (chartConfig) => {
  if (chart) chart.destroy(); // DESTROY CHART IF EXISTS

  var ctx = document.getElementById('chartJSContainer').getContext('2d');
  chart = new Chart(ctx, chartConfig);

  chart.update();
  option1 = !option1;
}

document.getElementById('myButton').addEventListener("click", () => {
  option1 ? addChart(options) : addChart(options2);
});
<body>
  <button id="myButton">
Gen Chart
</button>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Fiddle: https://jsfiddle.net/Leelenaleee/6gf0hs9q/19/

Upvotes: 1

Related Questions