[Chartjs]-Update Chart JS with date range selector

3๐Ÿ‘

โœ…

I had the same problem that you have.

In order to update the graph i am using two functions:

Remove all datasets in current graph:

function removeDataset(chart) {
   chart.data.datasets = [];
};

Add a new dataset to the graph:

function addDataset(chart, name, data, background, border, fill) {
    var newDataset = {
        label: name,
        data: [],
        backgroundColor: background,
        borderColor: border,
        fill: fill
    };
    for (var index = 0; index < data.length; ++index) {
        newDataset.data.push(data[index]);
    }
    chart.data.datasets.push(newDataset);
};

So, when i have the ajax done, i use like this:

removeDataset(ctx1);
addDataset(ctx1, "Dataset Name", resp.dataset_data_json, "#007bff", "#007bff", true);  
ctx1.update();

To declare the graph, i use:

var ctx1;
$(document).ready(function () {
    var canvas1 = $("#canvas1")[0];   
    canvas1.height = "300";             
    ctx1 = new Chart(canvas1, config_ctx1);
});

I hope it helps.

Leave a comment