You can use addData and removeData, see addData adds only one dataset per call, but removeData removes all datasets from chart. There is also way to push label and dataset see codepen sample:

First what you need is to save your chart in variable, so you can easy add and remove data. when you have chart saved in var, let's say myChart, you can call removeData() like: myChart.removeData(). For adding data you have to send label and data like: myChart.addData('news', [2, 32, 3]).

The idea is next, to update chart when your ajax call is success. The important thing is to have chart instance in same file where you have ajax call, you should move onclick call to js file, or call function from from àpp.js.

Now depends on your data structure, you will need to go through each and get value and label. You have to get same result from data like you have when you're creating chart.


What you will have in app.js


        url: "http://localhost/chartjs/data.php",
        method: "GET",
        success: function(data) {
            var op1 = [];
            var op2 = [];

            let data_keys = Object.keys(data[0])
            first = data_keys[0] //1st element
            second = data_keys[1] //2nd element

            for(var i in data) {


         var chartdata = {
         labels: op1,
         datasets : [
             label: 'SystemID and Apparent Power (VA)',
             backgroundColor: 'rgba(250, 50, 50, 0.4)',
             borderColor: 'rgba(500, 50, 50, 0.5)',
             hoverBackgroundColor: 'rgba(500, 30, 30, 0.2)',
             hoverBorderColor: 'rgba(500, 30, 30, 0.3)',
             data: op2

  var ctx = document.getElementById('mycanvas').getContext('2d');

  var barGraph = new Chart(ctx, {
    type: 'line',
    data: chartdata,
    options: {
    scales: {
       xAxes: [{
               ticks: {
                fontSize: 10
        yAxes: [{
            ticks: {
                fontSize: 10
    error: function(data) {

    function updateChartAjaxCall(data1, data2)
        //ajax call here 
            type: 'POST',
            url: 'data.php',
            dataType: 'html',
            data: {data1:data1,data2:data2},
                // here also manipulate data what you get to update chart propertly
                myChart.addData('newLabel', [23, 33, 4]);
            error:function (xhr, ajaxOptions, thrownError){
            complete: function(){

Then you bargraph.html will be also changed:

<script type="text/javascript">

    var data1=$("#data1").val();
    var data2=$("#data2").val();

    updateChartAjaxCall(data1, data2);

Related Query

More Query from same tag