Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Is there any better way to achieve same thing?

My JS Code:

var chart_= function () {

    $('#canvas_id').replaceWith('<canvas id="canvas_id" style="height:280px"></canvas>');
    $.ajax({
        type: 'POST', //post method
        url: 'url', //ajaxformexample url
        dataType: "json",
        success: function (result, textStatus, jqXHR)
        {
            // GENERATE CHART DATA
            var labels = result.obj.map(function (e) {
                return e.label;
            });
            var data = result.obj.map(function (e) {
                return e.data;
            });
            new Chart($("#canvas_id"), {
                type: 'bar',
                options: options_object,
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: "",
                            backgroundColor: '#00c0ef',
                            data: data
                        }
                    ]
                }

            });

        }
    });
};
like image 734
ansh Avatar asked Jul 29 '17 07:07

ansh


1 Answers

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!

like image 177
John Townsend Avatar answered Nov 15 '22 20:11

John Townsend