[Chartjs]-How to get the database data into ChartJS using codeigniter

2👍

I use chart.js, and I think I’m doing exactly what you want to do, which is to have ajax fetch the chart data, and then display it. You do have to update the chart a special way, and hopefully my code below will show you what you need to do. I think the key here is right up at the top, in the funcs namespace, the updateMyChart function. Check it out:

(function($){
    // Local namespaced variables and functions
    var namespace = {
        myChart: null,
        updateMyChart: function(data){
            funcs.myChart.data.datasets[0].data = data;
            funcs.myChart.update();
        }
    };
    // End local namespaced variables and functions
    window.funcs = ( window.funcs ) 
        ? $.extend( window.funcs, namespace ) 
        : namespace;
})(this.jQuery);

/* Document ready function */
$(document).ready(function(){

    // Initial config
    var myChartConfig = {
        type: 'bar',
        data: {
            labels: ['Yes', 'No', 'Maybe'],
            datasets: [{
                label: 'Current Count',
                backgroundColor: [
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(75, 192, 192, 0.2)'
                ],
                borderColor: [
                    'rgba(75, 192, 192, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(75, 192, 192, 1)'
                ],
                borderWidth: 1,
                data: [0,0,0]
            }]
        },
        options: {}
    };

    var myChartCanvas = $("#myChart");
    funcs.myChart = new Chart(myChartCanvas, myChartConfig);

    /* Unit selector for interest */
    $('#btnchart').on('click', function(){
        $.ajax({
            type: 'post',
            cache: false,
            url: '/someplace/special',
            data: {},
            dataType: 'json',
            success: function(response){
                if(response.data){
                    // In PHP I just json_encode(['data' => [SOME DATA]]);
                    funcs.updateMyChart(response.data);
                }
            },
            error: function(){
                alert('An error prevented chart awesomeness.');
            }
        });
    });

});

I know I’m using jQuery and you might not be, but the updating doesn’t really have anything to do with jQuery anyways.

Leave a comment