Popular Chart.JS with Mysql data passed in the page render by an async function

Asked

Viewed 563 times

-2

Speak people, I’m wanting to popular a pie chart on my Dashboard page, but I’m not getting, can help me (I don’t want to use php, only javascript, jquery and html).

  • Chart: Chart.JS
  • BD: Mysql
  • Language: Javascript / Node.JS

My route on which I pass Json in the page render:

pageAdmin: (req, res) => {
  (async function () {
    let teste = await DBModel.getTeste();

    res.render('./pageAdmin', {
       //Dados que são passados para a página
       DTTeste: JSON.parse(JSON.stringify(teste))
    });

  })();//async
};

Here my ejs file where I rescan the chart (front-end):

<div class="row">
   <div style="padding:10px" id="chart-container">
        <canvas id="pie-chart" width="800" height="450"></canvas>
   </div>
</div>

And finally the excerpt that contains the script to generate and popular the graph:

<script>
    new Chart(document.getElementById("pie-chart"), {
        type: 'pie',
        data: {
            labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
            datasets: [{
                label: "Population (millions)",
                backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"],
                data: [2478, 5267, 734, 784, 433]
            }]
        },
        options: {
            title: {
                display: true,
                text: 'Predicted world population (millions) in 2050'
            }
        }
    });
</script>

How do I popular the chart label and date using the "Dtteste" received in the render?

The data is coming this way (looking at the console.log):

inserir a descrição da imagem aqui

where "status"_rnc will be the chart label and "Qtde" will be the values

1 answer

0


I got:

inserir a descrição da imagem aqui

Follow code with the solution:

<!-- Pizza total peças por perfil no dia -->
<script>

    //Variáveis que receberão os dados para popular o gráfico
    const linhaProducao = [];
    const pecasProduzidas = [];

    //Dados recebidos do res.render na rota
    '<% DTTotalPecasPorPerfil.forEach((row, index) => { %>'
        linhaProducao.push('<%- row.Perfil %>');
        pecasProduzidas.push('<%- row.Total %>');
    '<% }); %>'

    //Doughnut chart definido no canvas da página
    //var ctx = document.getElementById('pie-chart').getContext('2d');
    var canvas = document.getElementById('pie-chart');
    var ctx = canvas.getContext("2d");

    //Iniciando o gráfico
    var myChart = new Chart(ctx, {
        type: 'doughnut',//Tipo de gráfico
        maintainAspectRatio: true,
        responsive: true,
        data: {
            labels: linhaProducao,//Texto agrupador
            datasets: [{
                data: pecasProduzidas,//Valores
                backgroundColor: ["#007bff", "#ffc107", "#28a745", "#702CA1"],//Cores
                borderWidth: 0.9,
                borderColor: '#FFFFFF',
            }]
        },
        options: {
            title: {
                display: false,
                text: 'Titulo aqui',
                position: 'top',
                fontSize: 16,
                fontColor: '#000000',
                padding: 20,
            },
            animation: {
                animateScale: true,
                animateRotate: true,
            },
            legend: {
                display: true,
                position: 'right',
                labels: {
                    size: 14,
                    lineHeight: 1.6,
                    boxWidth: 20,
                    fontColor: '#181B22',
                    padding: 12,
                }
            },
            tooltips: {
                enabled: true,
            },
            plugins: {
                datalabels: {
                    color: '#FFFFFF',
                    textAlign: 'center',
                    font: {
                        size: 14,
                        weight: 'bold',
                        lineHeight: 1.6,
                    },
                    formatter: function (value, ctx) {
                        //return ctx.chart.data.labels[ctx.dataIndex] + '\n' + value;
                        return value;
                    }
                }
            },
        },
    });
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.