Chartjs-How to render multiple Chart.JS charts on the same page with AJAX data and variables

1👍

I found a way using an .each function after piecing together various answers to similar questions. This JS is called for each chart whenever there is a canvas with a “line” class on the page. Hopefully this will be of help to others.

$('.line').each(function (index, element) {

var kpidata = element.getAttribute('id');


$.ajax({

    type: "POST",
    url: "/Home/GetLineChartData",
    traditional: true,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: kpidata,
    success: function (iData) {
        var aData = iData;
        var aLabels = aData[0];
        var aDatasets1 = aData[1];
        var dataT = {
            labels: aLabels,
            datasets: [{

                data: aDatasets1,
                label: 'Value',
                backgroundColor: getStyle('--primary'),
                borderColor: 'rgba(255,255,255,.55)'
            }]
        };


        var ctx = element.getContext('2d');

        var myNewChart = new Chart(ctx, {
            type: 'line',
            data: dataT,
            options: {
                responsive: true,
                tooltipCaretSize: 0,
                maintainAspectRatio: false,
                legend: {
                    display: false
                },
                scales: {
                    xAxes: [{
                        gridLines: {
                            color: 'transparent',
                            zeroLineColor: 'transparent'
                        },
                        ticks: {
                            fontSize: 2,
                            fontColor: 'transparent'
                        }
                    }],
                    yAxes: [{
                        display: false,
                        ticks: {
                            display: false

                        }
                    }]
                },
                elements: {
                    line: {
                        borderWidth: 1
                    },
                    point: {
                        radius: 4,
                        hitRadius: 10,
                        hoverRadius: 4
                    }
                }
            }


        }
        );
    }
});


});

Leave a comment