Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJs chart won't update new values

first and foremost, sorry about the broken english.

I'm using ChartJS to generate charts for a while, but today I stumbled in a problem that I can't seem to find an answer. I'm using a function to add data dynamically to my chart, then update it. It's working when I need to just add another dataset, but when I try to edit an existing dataset, I can get the values (seems like correctly) to the chart dataset, however, the chart won't show the new values, even after a update().

HTML:

  <div class="row">
    <img id="loading1" class="loading" src="resources/img/loading2.gif" hidden>
    <div id="chart1-wrapper" class="chart-wrapper">
      <canvas id="chart1"></canvas>
    </div>
  </div>
  <script>
    var ctx = document.id("chart1").getContext("2d");
    var chart1 = create_chart("chart title", "label text", "bar"); //Custom code that just create an empty chart;
  </script>

Function that creates the chart:

function create_chart(title, label_prefix, type) {
  var data = {
    labels: [],
    datasets: []
  };
  var options = {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    legend: {
      display: true
    },
    title: {
      display: true,
      text: title
    },
    tooltips: {
      intersect: false,
      mode: 'x',
      callbacks: {
        title: function() {}
      }
    },
    maintainAspectRatio: false,
    onClick: handleClick
  };
  var chart = new Chart(ctx, {
    type: type,
    data: data,
    options: options
  });
  return chart;
}

Here is my Update script:

function updateChart1(data, sigla){
            var dtsts;
            if(data != null){
                if(chart1.data.datasets.length == 0){
                    dtsts = [];
                    jQuery.each(JSON.parse(data), function(index, val){
                        var media = (val.soma_duracao/val.count_prot)/3600;
                        var dt_item = {
                            label: getMes(val.mes),
                            data: [media],
                            backgroundColor: [(pallete[0].rgba)],
                            borderColor: [(pallete[0].rgba.replace('0.7', '1'))],
                            borderWidth: 2
                        }
                        dtsts.push(dt_item);                        
                    });
                    console.log(dtsts);
                    chart1.data.labels = ['hours'];
                    chart1.options.title.text = "foo bar";
                    chart1.options.title.display = true;
                    chart1.options.legend = true;
                    chart1.options.tooltips.callbacks.label = function(tooltipItems, data) {
                        return tooltipItems.yLabel.toFixed(2) + " hours";
                    }                           
                } else {
                    dtsts = chart1.data.datasets;                               
                    jQuery.each(JSON.parse(data), function(index, val){
                        var media = (val.soma_duracao/val.count_prot)/3600;
                        dtsts[index].data.push(media);
                        dtsts[index].backgroundColor.push(pallete[1].rgba);
                        dtsts[index].borderColor.push(pallete[1].rgba.replace('0.7', '1'));
                    });
                    console.log(dtsts);
                }
                chart1.data.datasets = dtsts;                   
            }
            chart1.update();
        }

Running the script the first time I get this:

data:Array(1)
0:83.83071111111111
length:1
pop:ƒ ()
push:ƒ ()
shift:ƒ ()
splice:ƒ ()
unshift:ƒ ()
_chartjs: {listeners: Array(1)}
__proto__: Array(0)

Running it again updates my data:

data:Array(2)
0:83.83071111111111
1:13.746988158477201
length:2
pop:ƒ ()
push:ƒ ()
shift:ƒ ()
splice:ƒ ()
unshift:ƒ ()
_chartjs:{listeners: Array(1)}
__proto__:Array(0)

This is the correct value for my data, however, the chart simply won't update to show the values.

I'm not sure if it is some stupid mistake, but I'm just lost at this point. If anyone can shed a light, would be great. Thanks!

(PS: if you guys need any more info, please let me know)

Edit Just to clarify, I need both datas in the same dataset after the update, 2 bars of data.

like image 311
urukh Avatar asked Mar 16 '26 15:03

urukh


1 Answers

I need the second update of the chart after printing (I use another background colors in black and white print). Ordinary .update method didn't help update chart. I used setTimeout with 0.

 setTimeout(function(){
   myChart.data.datasets[0].backgroundColor = ['#f2d13a', '#c9deeb', '#cacaca'];
   myChart.update();
 }, 0);
like image 173
Victoria Husaruk Avatar answered Mar 18 '26 04:03

Victoria Husaruk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!