[Chartjs]-Chart.js load new data from saved JSON object

2👍

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>
  

Leave a comment