Andyweb
Andyweb

Reputation: 172

Chart.js load new data from saved JSON object

So the easiest way to explain this issue, is to see the example I've created at http://jsfiddle.net/andywebo/d6fskqpx/18/

So what I'm trying to achieve is that every time a new date period is selected from the dropdown the graph updates with the new dataset and labels (JSON data here: http://myjson.com/1d6l2o).

<select name="search_period" id="search_period" data-src="https://api.myjson.com/bins/1d6l2o">
   <option value="day">Day</option>
   <option value="week">Week</option>
   <option value="month" selected>Month</option>
   <option value="year">Year</option>                     
</select>

It works the 1st time around, but if you select the 'month' time period that's been initially selected, the jsonData that I've attempted to save (same happens for any date period that I set as selected)

var chart; 
var ctx = document.getElementById("searchChart").getContext("2d");   

var initPeriod = $('#search_period').val();
var jsonURL = $('#search_period').data('src'); 
var jsonData; 

$.getJSON( jsonURL, function( results ) {
   chart = new Chart(ctx, {
    data: results[initPeriod],
    ...
   });
   jsonData = results;
});

$('#search_period').change(function(){
  var activePeriod = $(this).val();

  removeAllData(chart);      

  addNewData(chart, jsonData[activePeriod]);

});

...seems to get modified by the removeAllData function - I can see the 'month' data being removed in the console

function removeAllData(chart) {     
  chart.data.labels.length = 0;
  chart.data.datasets.length = 0;
}

The only way I've found around this is to re-fetch the data every time a new time period is selected, but that's hardly ideal!

Bonus question: Any ideas why the chart would not animate each time a previously selected date period is selected?

Upvotes: 3

Views: 2395

Answers (1)

rafaelcastrocouto
rafaelcastrocouto

Reputation: 12161

It's way easier to just destroy and render a new chart. The chart.update method works better to manage small pieces of data, like adding or removing a few points.

You just need to call chart.destroy and run your chart creation function again.

$(function(){  

  var chart; 
  var ctx = document.getElementById("searchChart").getContext("2d");
  var initPeriod = $('#search_period').val();
  var jsonURL = $('#search_period').data('src'); 
  var jsonData;

  var initChart = function (data) {
    chart = new Chart(ctx, {       
      type: 'line',        
      data: data,       
      options: {
        responsive: true,
        legend: {
          display: false
        },
        elements:{
          point:{
            radius:0
          }
        },
        scales:{
          xAxes:[
            {
              gridLines:{
                display:false
              }
            }
          ],
          yAxes:[
            {
              ticks: {
                beginAtZero: true
              }
            }
          ]
        }
      }
    });  
  };
  
  // fetch data
  $.getJSON( jsonURL, function( results ) {
    // copy json object
    jsonData = results;     
    // init chart
    initChart(results[initPeriod])
  });

  // on new period select
  $('#search_period').change(function(){
    // get new period
    var activePeriod = $(this).val();
    // render chart again
    initChart(jsonData[activePeriod]);
  });


});
.panel-searches__graph{
  margin:20px 0 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>

<select name="search_period" id="search_period" data-src="https://api.myjson.com/bins/1d6l2o">
  <option value="day">Day</option>
  <option value="week">Week</option>
  <option value="month" selected>Month</option>
  <option value="year">Year</option>                     
 </select>

<div class="panel-searches__graph">
  <canvas id="searchChart" width="500" height="150"></canvas>
</div>
  

Upvotes: 2

Related Questions