Chartjs-How do I make a pie chart showing number of people in an age group with JSON and ChartJS?

0👍

Figured it out myself after following Nagib’s comment link.

Just leaving it here in case anyone else is trying the same thing.

$(document).ready(function () {
    $.ajax({
        type: "Get",
        url: "/?handler=ageData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            var datatf = response.below35;
            var datafn = response.below49;
            var dataff = response.below55;
            var dataso = response.below60;
            var datasf = response.below65;
            var dataasf = response.above65;

            var cage = document.getElementById('ageChart').getContext('2d');
            var ageChart = new Chart(cage, {
                type: 'pie',
                data: {
                    labels: ['< 36', '36 - 49', '50 - 55', '56 - 60', '61 - 65', '> 65'],
                    datasets: [{
                        label: 'Age Group',
                        data: [datatf, datafn, dataff, dataso, datasf, dataasf],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
    });
});

And in my handler, the variables are the same as the one in the question and called it with JsonResult {...below35 = lessthreefive...}

End result
enter image description here

Leave a comment