Skip to content Skip to sidebar Skip to footer

Refresh The Bar Char In ChartJS (v2.6.0) Using Ajax Correct Way

I am refreshing my Bar Chart on change of a drop down. I just Want to know that am I doing it in correct way. In my code every time I am replacing my existing canvas with new one.

Solution 1:

Definitely some better ways, I have been using Chart.js for some live updating charts and a good way to accomplish what you want is to declare an chart with some of the settings predefined initially.

var chart = new Chart( canvas, {
          type: "bar",
          data: {}
          options: {}
}

This way, whenever you need to update the chart, you just access the already existing chart. And update the data to what you get from your ajax call, and use the chart.update() method, so you can keep using the pre-existing canvas

$.ajax({
    type: 'POST', //post method
    url: 'url', //ajaxformexample url
    dataType: "json",
    success: function (result, textStatus, jqXHR)
    {
        chart.data = result;
        chart.update();
    }
});

Hope this helps!


Post a Comment for "Refresh The Bar Char In ChartJS (v2.6.0) Using Ajax Correct Way"