[Chartjs]-Drawing chart.js with external JSON

3đź‘Ť

I messed around with it and got it working (at least for me)

The notable parts I changed were the ajax:

$.ajax({url:"data.json",dataType:"json"})
  .fail(function(){alert("Im a failure")})
  .done(function(data){
  var myData = (data);

and I took the end part out of the “window.onload”, which wasn’t neccesary since you’d already declared the canvas.

I guess I’ll dump all the code I used

<script src="Chart.js"></script>
<script src="jquery-1.11.2.min.js"></script>
</head>
<body>
<div id="chartCanvas">
 <canvas id="canvas"></canvas>
 <br>
</div>


<script type="text/javascript">
$.ajax({url:"data.json",dataType:"json"})
  .fail(function(){alert("Im a failure")})
  .done(function(data){
  var myData = (data);
  console.log(myData[0].jaar);
Array.prototype.mapProperty = function(property) {
      return this.map(function (obj) {
       return obj[property];
      });

     };

// Example: myData.mapProperty('rank') to get an array of all ranks 
 lineChartData = {
    labels : myData.mapProperty('jaar'),
     datasets : [
       {
   label: "My First dataset",
   fillColor : "rgba(220,220,220,0.2)",
   strokeColor : "rgba(220,220,220,1)",
   pointColor : "rgba(220,220,220,1)",
   pointStrokeColor : "#fff",
   pointHighlightFill : "#fff",
   pointHighlightStroke : "rgba(220,220,220,1)",
   data : myData.mapProperty('verbruikInGB')
  }
       ]
  };

 //window.onload = function(){
console.log("cheerio")
 var ctx = document.getElementById("canvas").getContext("2d");
 window.myLine = new Chart(ctx).Line(lineChartData);
 //}  

});

Leave a comment