Populating Chart.js with AJAX request data

Asked

Viewed 4,048 times

1

Hello,

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

Within my system, when the user logs in, a query is made in my database through AJAX request that filters the data and returns it, filling certain gaps of the present content. As in the code below, see 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 view more specific data, he leaves for the dropdown selectors that act in the same way, restoring 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 would like to know how I can put, for example, values within data['0']['cpfsEnviados] within its proper location within the data in my chart script. Note that in my success I even put a code to recalculate the chart’s canvas to try to visualize some change, but nothing.

Any idea, suggestion, solution?

Thank you very much!

1 answer

2


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

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

// 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();
    }
});
  • Good @Rafael Mafra, they have no relationship, they are in . Different js and yes, the request data should replace the graphic values! Could you give an example of what you said? I didn’t understand very well.

  • When you call the function gerarGraficos, the data stored in the variables will be used dataLine and dataBar. If you want to change the chart data that has already been generated, you need to configure new data in the variables and call gerarGraficos again. Here is an example: https://jsfiddle.net/cxtfmpjo/1/

  • I understood what you meant. But in the case exemplified, you are just reloading the chart by means of predefined data. And in my case I need the data to come from the AJAX request Success? How to call the data?

  • Now I understand what you really want. I will edit my answer.

  • Thanks @Rafael, I’m waiting for the answer!

  • You need to update the variables dataBar and dataLine as soon as the callback success is called, for this these two variables need to be in the same scope as the ajax request $.ajax.

  • I don’t understand @Rafael, could exemplify?

  • I don’t know what the data structure is like on the server so I can’t help you any more than that.

Show 4 more comments

Browser other questions tagged

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