[Chartjs]-Using ajax populate dynamic piechart from chartjs

1👍

You could accomplish this in the following way …

// for demonstration purposes only
// use response.d in real case scenario
var response = [{ "clinic_name": "Clinic 1", "total_checked_up": "10" }, { "clinic_name": "Clinic 2", "total_checked_up": "20" }, { "clinic_name": "Clinic 3", "total_checked_up": "30" }, { "clinic_name": "Clinic 4", "total_checked_up": "40" }]; // response from ajax request

OnSuccess_(response);

function OnSuccess_(response) {
    var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
    var pieChart = new Chart(pieChartCanvas);
    var PieData = [];
  
    // create PieData dynamically
    response.forEach(function(e) {
        var random_color = '#' + Math.floor(Math.random() * 16777215).toString(16);
        PieData.push({
            value: e.total_checked_up,
            color: random_color,
            highlight: random_color,
            label: e.clinic_name
        });
    });
  
    var pieOptions = {
        //Boolean - Whether we should show a stroke on each segment
        segmentShowStroke: true,
        //String - The colour of each segment stroke
        segmentStrokeColor: "#fff",
        //Number - The width of each segment stroke
        segmentStrokeWidth: 2,
        //Number - The percentage of the chart that we cut out of the middle
        percentageInnerCutout: 0, // This is 0 for Pie charts
        //Number - Amount of animation steps
        animationSteps: 100,
        //String - Animation easing effect
        animationEasing: "easeOutBounce",
        //Boolean - Whether we animate the rotation of the Doughnut
        animateRotate: true,
        //Boolean - Whether we animate scaling the Doughnut from the centre
        animateScale: false,
        //Boolean - whether to make the chart responsive to window resizing
        responsive: true,
        // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
        maintainAspectRatio: true,
        //String - A legend template
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
    };
  
    //Create pie or douhnut chart
    // You can switch between pie and douhnut using the method below.
    pieChart.Doughnut(PieData, pieOptions);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="pieChart"></canvas>

Leave a comment