score:2

Accepted answer

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.


Related Query

More Query from same tag