load new data for chart - Javascript Chart.js

Javascript examples for Chart.js:Chart Data

Description

load new data for chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  w  ww  .  j  a va 2s . c  om*/
$(document).ready(function(){
        var canvas = document.getElementById('linechart');
        var ctx = canvas.getContext('2d');
        var current = [800, 1350, 1400, 1600, 2600, 3100];
        var forecast = [400, 1050, 1200, 1300, 1800, 2400];
        var datasets = [{
            label: "current",
            backgroundColor: "rgba(220,220,220,0)",
            borderColor: "#7bc775",
            pointBackgroundColor: "#7bc775",
            data: current,
          },
          {
            label: "forecast",
            backgroundColor: "rgba(151,187,205,0)",
            borderColor: "#fed477",
            pointBackgroundColor: "#fed477",
            data: forecast,
          }];
        var currentData = [datasets[0]];
        var data = {
          labels: ["2", "4", "8", "12", "16", "20"],
          pointDotRadius: 0,
          pointRadius: 0,
          pointBorderWidth : 0,
          pointHitRadius: 0,
          datasets: currentData
        };
        var step  = 800;
        var max   = 3200;
        var start = 0;
        var config = {
           type: 'line',
          data : data
        };
        var mychart = new Chart(ctx,config);
        $('.selector').click(function(){
          data.datasets = [datasets[$(this).data('index')]];
          if(mychart!== null){
            mychart.destroy();
            mychart = new Chart(ctx, config);
          }
        });
      });
    }

      </script> 
   </head> 
   <body> 
      <canvas id="linechart"></canvas> 
      <div> 
         <a id="current" class="selector" data-index="0">Current</a> 
         <a id="forecast" class="selector" data-index="1">Forecast</a> 
      </div>  
   </body>
</html>

Related Tutorials