Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Many Flots using ChartJS and Ajax get data values

I’m using ChartJS to make charts and I have multiple charts on the same page. All of them are being generated successfully. But I’m having an error on the console indicating an error in ChartJS.

When I leave only 1 graphic on the page, it doesn’t show the error on the console, however, if I put 1 more, the error on the console is displayed.

I’ve already checked the HTML, and no canvas elements are duplicated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

what am I doing wrong?

Error

chart.min.js:13 Uncaught Error: Canvas is already in use. Chart with ID '1' must be destroyed before the canvas can be reused.
at new hn (chart.min.js:13)
at Object.<anonymous> (Dashboard.js:145)
at Function.each (js?v=LCTUWYjF9I-Sw3l0P8Zn6_b6478OuizeBkjnoe30Tcc1:1)
at i.fn.init.each (js?v=LCTUWYjF9I-Sw3l0P8Zn6_b6478OuizeBkjnoe30Tcc1:1)
at Object.success (Dashboard.js:133)
at c (js?v=LCTUWYjF9I-Sw3l0P8Zn6_b6478OuizeBkjnoe30Tcc1:1)
at Object.fireWith [as resolveWith] (js?v=LCTUWYjF9I-Sw3l0P8Zn6_b6478OuizeBkjnoe30Tcc1:1)
at b (js?v=LCTUWYjF9I-Sw3l0P8Zn6_b6478OuizeBkjnoe30Tcc1:1)
at XMLHttpRequest.<anonymous> (js?v=LCTUWYjF9I-Sw3l0P8Zn6_b6478OuizeBkjnoe30Tcc1:1)

HTML

<div class="row">
<div class="col-lg-6">
    <div class="ibox float-e-margins">
        <div class="ibox-title">
            <h5>Matchs dos Últimos Processos Executados</h5>
            <div class="ibox-tools">
                <a class="collapse-link">
                    <i class="fa fa-chevron-up"></i>
                </a>
                <a class="close-link">
                    <i class="fa fa-times"></i>
                </a>
            </div>
        </div>
        <div class="ibox-content">
            <canvas id="ultimosProcessosExecutados" height="170"></canvas>
        </div>
    </div>
</div>
<div class="col-lg-6">
    <div class="ibox float-e-margins">
        <div class="ibox-title">
            <h5>Matchs por Empresa Origem</h5>
            <div class="ibox-tools">
                <a class="collapse-link">
                    <i class="fa fa-chevron-up"></i>
                </a>
                <a class="close-link">
                    <i class="fa fa-times"></i>
                </a>
            </div>
        </div>
        <div class="ibox-content">
            <canvas id="divValorMedioPorEmpresaDeOrigem" height="170"></canvas>
        </div>
    </div>
</div>

JS

$(document).ready(function () {
    VisaoGeralProcessamento();    
    UltimosProcessosExecutados();    
    ValorMedioPorEmpresaDeOrigem();
});

function perc2color(perc) {
    var r, g, b = 0;
    if (perc < 50) {
        r = 255;
        g = Math.round(5.1 * perc);
    }
    else {
        g = 255;
        r = Math.round(510 - 5.10 * perc);
    }
    var h = r * 0x10000 + g * 0x100 + b * 0x1;
    return '#' + ('000000' + h.toString(16)).slice(-6);
}

function UltimosProcessosExecutados() {    
    $.ajax({
        url: '/ProcessoIA/DadosDashboard',
        type: 'GET',
        data: {
            'grafico': ""
        },
        success: function (data) {
            var rotulos = [];
            var dados = [];

            $(data.dados).each(function (index, item) {
                rotulos.push(item.Chave);
                dados.push(item.Valor);
            });

            var chartUltimosProcessosExecutados = document.getElementById('ultimosProcessosExecutados').getContext('2d');
            new Chart(chartUltimosProcessosExecutados, {
                type: 'line',
                data: {
                    labels: rotulos,
                    datasets: [{
                        label: 'Valor Médio dos Matchs (%)',
                        data: dados,
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            suggestedMax: 100
                        }
                    }
                }
            });
        },
        error: function (request, error) {
            alert("Request: " + JSON.stringify(request));
        }
    });
}

function ValorMedioPorEmpresaDeOrigem() {
    $.ajax({
        url: '/ProcessoIA/DadosDashboard',
        type: 'GET',
        data: {
            'grafico': "ValorMedioPorEmpresaDeOrigem",
        },
        success: function (data) {
            $(data.dados).each(function (index, item) {
                var rotulos = [];
                var dados = [];
                var coresDeFundo = [];

                $(data.dados).each(function (index, item) {
                    rotulos.push(item.Chave);
                    dados.push(item.Valor);
                    coresDeFundo.push(perc2color(item.Valor));
                });

                var chartValorMedioPorEmpresaDeOrigem = document.getElementById('divValorMedioPorEmpresaDeOrigem').getContext('2d');
                new Chart(chartValorMedioPorEmpresaDeOrigem, {
                    type: 'bar',
                    data: {
                        labels: rotulos,
                        datasets: [{
                            label: 'Valor Médio dos Matchs (%)',
                            data: dados,
                            borderColor: coresDeFundo,
                            backgroundColor: coresDeFundo,
                            tension: 0.1
                        }]
                    }
                });
            });
        },
        error: function (request, error) {
            alert("Request: " + JSON.stringify(request));
        }
    });
};

>Solution :

You have to recreate the canvas again for each call in AJAX, try to destroy the canvas and create it for each call

    $(document).ready(function () {
        VisaoGeralProcessamento();    
        UltimosProcessosExecutados();    
        ValorMedioPorEmpresaDeOrigem();
    });
    
    let chart1;
    let chart2;

    function perc2color(perc) {
        var r, g, b = 0;
        if (perc < 50) {
            r = 255;
            g = Math.round(5.1 * perc);
        }
        else {
            g = 255;
            r = Math.round(510 - 5.10 * perc);
        }
        var h = r * 0x10000 + g * 0x100 + b * 0x1;
        return '#' + ('000000' + h.toString(16)).slice(-6);
    }
    
    function UltimosProcessosExecutados() {    
        $.ajax({
            url: '/ProcessoIA/DadosDashboard',
            type: 'GET',
            data: {
                'grafico': ""
            },
            success: function (data) {
                var rotulos = [];
                var dados = [];
    
                $(data.dados).each(function (index, item) {
                    rotulos.push(item.Chave);
                    dados.push(item.Valor);
                });
    
                var chartUltimosProcessosExecutados = document.getElementById('ultimosProcessosExecutados').getContext('2d');
                    if (chart1) {
                        chart1.destroy();
                    }
                chart1 = new Chart(chartUltimosProcessosExecutados, {
                    type: 'line',
                    data: {
                        labels: rotulos,
                        datasets: [{
                            label: 'Valor Médio dos Matchs (%)',
                            data: dados,
                            borderColor: 'rgb(75, 192, 192)',
                            backgroundColor: 'rgb(75, 192, 192)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                suggestedMax: 100
                            }
                        }
                    }
                });
            },
            error: function (request, error) {
                alert("Request: " + JSON.stringify(request));
            }
        });
    }
    
    function ValorMedioPorEmpresaDeOrigem() {
        $.ajax({
            url: '/ProcessoIA/DadosDashboard',
            type: 'GET',
            data: {
                'grafico': "ValorMedioPorEmpresaDeOrigem",
            },
            success: function (data) {
                $(data.dados).each(function (index, item) {
                    var rotulos = [];
                    var dados = [];
                    var coresDeFundo = [];
    
                    $(data.dados).each(function (index, item) {
                        rotulos.push(item.Chave);
                        dados.push(item.Valor);
                        coresDeFundo.push(perc2color(item.Valor));
                    });
    
                    var chartValorMedioPorEmpresaDeOrigem = document.getElementById('divValorMedioPorEmpresaDeOrigem').getContext('2d');
                    if (chart2) {
                        chart2.destroy();
                    }

                    chart2 = new Chart(chartValorMedioPorEmpresaDeOrigem, {
                        type: 'bar',
                        data: {
                            labels: rotulos,
                            datasets: [{
                                label: 'Valor Médio dos Matchs (%)',
                                data: dados,
                                borderColor: coresDeFundo,
                                backgroundColor: coresDeFundo,
                                tension: 0.1
                            }]
                        }
                    });
                });
            },
            error: function (request, error) {
                alert("Request: " + JSON.stringify(request));
            }
        });
    };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading