0

I'm having trouble while trying to replace data inside my chart.js chart.

By now, that's how my chart is set:

    <script>

        var optionsBar = {
            responsive: true
        };

        var dataBar = {
            labels: [<?=$mesReferencia?>],
            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: [<?=$cpfsEnviados?>]
                },
                {
                    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: [<?=$propostasFinalizadas?>]
                },
                {
                    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: [<?=$propostasAprovadas?>]
                }
            ]
        };


        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: [<?=$propostasFinalizadas?>]
                },
                {
                    label: "Aprovadas",
                    fill: false,
                    backgroundColor: "rgba(255,246,0,0.6)",


  borderColor: "rgba(255,246,0,1)",                    
                borderWidth: 4,
                data: [<?=$propostasAprovadas?>]
            }
        ]
    };     

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

    function run(){
        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 = run;

    run();
</script>

See that the data used in the charts are from PHP vars. (Those are the values that feed my charts by default).

Then, I have a sequence of dropdown which filter data in my DB and return a javascript array object named data:

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();
    $(".mask-loading").fadeToggle(500);         
}

See that someplaces in my code are fed with the data returned in this array.

Everything is working pretty fine, but my only problem here is replacing the default PHP values from my chart with data[0]['example'] array and reloading the chart without refreshing the page. Any idea/ suggestions? Thanks!

jvbs
  • 417
  • 2
  • 11
  • 27
  • Maybe we could use some clarification: is the problem related to the initial set of data to be displayed upon page load? furthermore, from what you say, I understand that `data[0]['example']` should contain the following keys: `cpfsEnviados`, `propostasFinalizadas`, `propostasAprovadas`. Is that so? Maybe you just need to fire an AJAX request on page load: put it in `run()`, then the current content of `run()` would be moved to the AJAX success callback. Does that make sense? – Benito Dec 19 '16 at 18:23
  • Well @Benito, yes, the problem is related to the initial set because I want to show default data when the page loads. The 'example' can be any of the keys you said. The last part wasn't clear enough for me. – jvbs Dec 19 '16 at 18:33
  • Another thing that might help me understand: what kind of data are in the variables `$mesReferencia`, `$cpfsEnviados`, `$propostasFinalizadas` and `$propostasAprovadas`? integers, strings, arrays? – Benito Dec 20 '16 at 09:30
  • They're all integers @Benito – jvbs Dec 20 '16 at 11:05
  • Any update? Did you finally get it to work? – Benito Dec 21 '16 at 17:18
  • @Benito, my console returns that BarChart2 and LineChart are not defined. – jvbs Dec 21 '16 at 18:41
  • The code you sent below was added right down the code i already had Just to keep you in touch, instead of loading the default data with PHP, i'm now using ajax returns to set the default data also. So, I guess it might help with the hole proccess.. – jvbs Dec 21 '16 at 18:51
  • BarChart2 and LineChart are defined inside the run() function. Hence they are not visible from outside this function. You could *declare* them at the beginning of your script. And then *use* them inside run(). Try that... Then I don't know where your AJAX code is located, with respect to the rest of the script? – Benito Dec 21 '16 at 19:08

1 Answers1

0

Forget what I told you in my first comment (about updating the run() function). I just hadn't catched what you were precisely trying to do.

So you have an initial set of data in you PHP vars, that you feed to your chart. You want to update this set of data (which I guess you should do in your AJAX success callback). This answer and the link it provides should point you in the right direction.

In your success callback, you can add something like that:

// Update points in the datasets
// index in datasets[] can be 0, 1 or 2 (three datasets for BarChart)
BarChart2.datasets[0].points[0].value = data[0]['cpfsEnviados'];
BarChart2.datasets[1].points[0].value = data[0]['propostasFinalizadas'];
BarChart2.datasets[2].points[0].value = data[0]['propostasAprovadas'];
BarChart2.update();

// index in datasets[] can be 0 or 1 (two datasets for LineChar)
LineChart.datasets[0].points[0].value = data[0]['propostasFinalizadas'];
LineChart.datasets[1].points[0].value = data[0]['propostasAprovadas'];
LineChart.update();

Let me know if it is what you were looking for. Also, simple remark, in many JavaScript coding conventions you would avoid having the first letter of a variable as a capital. Hence maybe you should rename your charts variables to barChart2 and lineChart.

Community
  • 1
  • 1
Benito
  • 710
  • 5
  • 10