Populating Chart.js with AJAX request data

1

Hello,

First I'll give you a brief introduction to how my system works so you understand exactly what my difficulty is. Maybe it gets a little big, I'm sorry.

Within my system, when the user logs in, a query is made to my database through an AJAX request that filters the data and returns it, filling certain gaps of the present content. As in the code below, look at the ids that are changed by the data:

function inicializaDashboard(){
    $.ajax({
        url: 'datacenter/functions/inicializaDashboard.php',
        async: true,
        type: 'POST',
        dataType: 'JSON',
        data: {rede: '9999999', codLoja: '9999999', mes: '9999999'},
        success: function(data){
            //console.log(data);
            $("#filtro-rede").text(data[0]['rede']);
            $("#filtro-loja").text(data[0]['loja']);
            $("#filtro-mes").text(data[0]['mesReferencia']);
            $('#cpfsEnviados').text(data[0]['cpfsEnviados']);
            $("#finalizadas").text(data[0]['propostasFinalizadas']);
            $("#aprovadas").text(data[0]['propostasAprovadas']);
            $("#indiceAprovacao").text(data[0]['indiceAprovacao']+'%');
            $("#primeirasCompras").text(data[0]['primeirasCompras']);
            $("#segurosQnt").text(data[0]['seguros']);
        },
        error: function(data){
            console.log('Ocorreu um erro durante a execução do dashboard: '+ data);
        }
    });
}

And so the data is shown, but if the user wants to see more specific data, it departs to the dropdown selectors that act in the same way, resetting the data in question:

$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(500);
    $.ajax({
        url: 'datacenter/functions/filtraDashboardGeral.php',
        async: true,
        type: 'POST',
        dataType: 'JSON',
        data: {rede: $("#dropdown-parceria").val(), codLoja: $("#dropdown-loja").val(), mes: $("#dropdown-mes").val()},
        success: function(data){
            //console.log(data);
            $("#filtro-rede").text(data[0]['rede']);
            $("#filtro-loja").text(data[0]['loja']);
            $("#filtro-mes").text(data[0]['mesReferencia']);
            $('#cpfsEnviados').text(data[0]['cpfsEnviados']);
            $("#finalizadas").text(data[0]['propostasFinalizadas']);
            $("#aprovadas").text(data[0]['propostasAprovadas']);
            $("#indiceAprovacao").text(data[0]['indiceAprovacao']+'%');
            $("#primeirasCompras").text(data[0]['primeirasCompras']);
            $("#segurosQnt").text(data[0]['seguros']);
            mascararFiltros();
            $('#graficoBarra').replaceWith('<canvas id="graficoBarra"></canvas>');
            $('#graficoLinha').replaceWith('<canvas id="graficoLinha"></canvas>');
            gerarGraficos();
            $(".mask-loading").fadeToggle(500);
        },
        error: function(){
            alert('Ocorreu um erro durante o processamento dos filtros. Tente novamente!');
            $(".mask-loading").fadeToggle(500); 
        }
    });
});

The code resembles a lot. And so far everything works perfectly, my difficulty is, I have this code that generates me two graphs of chart.js :

   //======================= INICIO GRAFICO BARRAS =====================================================================
        var optionsBar = {
            responsive: true
        };

        var dataBar = {
            labels: ['Outubro', 'Novembro', 'Dezembro'],
            datasets: [
                {
                    label: "CPF's Enviados",
                    backgroundColor: "rgba(0,51,90,0.8)",
                    borderColor: "rgba(0,51,90,0.9)",
                    borderWidth: 2,
                    hoverBackgroundColor: "rgba(0,51,90,0.9)",
                    hoverBorderColor: "rgba(0,51,90,1)",
                    data: [100,200,350]
                },
                {
                    label: "Propostas Finalizadas",
                    backgroundColor: "rgba(0,130,229,0.8)",
                    borderColor: "rgba(0,130,229,0.9)",
                    borderWidth: 2,
                    hoverBackgroundColor: "rgba(0,130,229,0.9)",
                    hoverBorderColor: "rgba(0,130,229,1)",
                    data: [50,65,72]
                },
                {
                    label: "Propostas Aprovadas",
                    backgroundColor: "rgba(43,139,74,0.8)",
                    borderColor: "rgba(43,139,74,0.9)",
                    borderWidth: 2,
                    hoverBackgroundColor: "rgba(43,139,74,0.9)",
                    hoverBorderColor: "rgba(43,139,74,1)",
                    data: [25,35,63]
                }
            ]
        };

    //======================= INICIO GRAFICO LINHAS =====================================================================

        var optionsLine = {
            responsive: true
        };

        var dataLine = {
            labels: [<?=$mesReferencia?>],
            datasets: [
                {
                    label: "Finalizadas",
                    fill: false,
                    backgroundColor: "rgba(255,108,0,0.7)",
                    borderColor: "rgba(255,108,0,1)",
                    borderWidth: 4,
                    data: [50,65,72]
                },
                {
                    label: "Aprovadas",
                    fill: false,
                    backgroundColor: "rgba(255,246,0,0.6)",
                    borderColor: "rgba(255,246,0,1)",                    
                    borderWidth: 4,
                    data: [25,35,63]              
}
            ]
        };     

    //======================= FUNÇÃO GERA GRÁFICOS =====================================================================

        function gerarGraficos(){
            var ctx = document.getElementById("graficoBarra").getContext("2d");
            var BarChart2 = new Chart(ctx, {
                  type: 'bar',
                  data: dataBar,
                  options: optionsBar
            });

            var ctx2 = document.getElementById("graficoLinha").getContext("2d");
            var LineChart = new Chart(ctx2, {
                  type: 'line',
                  data: dataLine,
                  options: optionsLine
            });
        }

        window.onload = gerarGraficos;

        gerarGraficos();

I'd like to know how I can put, for example, the values within data['0']['cpfsEnviados] within its due location within data in my script script. Note that in my success I even put a code to recalculate the graphic canvas to try to visualize some change, but nothing.

Any idea, suggestion, solution?

Thank you!

    
asked by anonymous 20.12.2016 / 19:55

1 answer

1

To render the graphics again, you only need to call the gerarGraficos function again. But since you want to be rendered with new data, the variables dataLine and dataBar need to be changed.

You need to make these variables in the same scope as the $.ajax function.

// dados pré-definidos
var dataBar = [];
var dataLine = [];

gerarGraficos();

$.ajax({
    url: 'URL...',
    success: function (data) {
        // faça o tratamento dos dados e atualize
        // as variáveis dos gráficos.

        dataBar = data;

        gerarGraficos();
    }
});
    
21.12.2016 / 22:16