Chartjs-How can plot graph using json data

1👍

Assuming your JSON is in the following format

{
    chart_data: [
        {
            std_name: ...,
            student_count: ...,
            ab_count: ...
        },
        {
            std_name: ...,
            student_count: ...,
            ab_count: ...
        }
    ] 
}

you need to construct your chart data object like so

var labelX = [];
var bar1 = [];
var bar2 = [];           
$.ajax({
    url:"<? echo base_url();?>Attendance/pre_chart", 
    dataType: 'json',      
    success:function(data) {

        for (var i = 0; i < data.chart_data.length; i++) {
            labelX.push(data.chart_data[i]["std_name"]);
            bar2.push(data.chart_data[i]["student_count"]);
            bar1.push(data.chart_data[i]["ab_count"]);  
        }

    } 
});

and finally (notice that I removed the parentheses around the objects we just constructed)

var Day = {
    labels: labelX,
    datasets: [
        {
            fillColor: "rgba(172,194,132,0.4)",
            strokeColor: "#ACC26D",
            pointColor: "#fff",
            pointStrokeColor: "#9DB86D",
            data: bar1
        },
        {
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data: bar2
        }
    ]
}

Leave a comment