user3022030
user3022030

Reputation: 25

Error when using chart.js

So i have a code that looks like that:

<head>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>

<script src="Chart.js"></script>

<script type="text/javascript">

$(function() {
  var a = 0,
  b = 0,
  c = 0,
  d = 0,
  e = 0,
  timeCff = 0,  //Firefox
  timeSff = 0,
  timeCop = 0,  //Opera
  timeSop = 0,
 $.get('test1.csv').done(function(data) {
  var i, 
      lines = data.split(/\r\n|\n/),
      line = lines[0].split(','),
      oS = line.indexOf('oS'),
      browName = line.indexOf('browName'),
      browVer = line.indexOf('browVer'),
      timeCanvas = line.indexOf('timeCanvas'),
      timeSvg = line.indexOf('timeSvg');
  for(i=1; i<lines.length; i++) {
      line = lines[i].split(',');
      if(line[browName] === 'Firefox') {
          a++;
          timeCff += parseFloat(line[timeCanvas], 10);
          timeSff += parseFloat(line[timeSvg], 10);
      }else if(line[browName] === 'Opera') {
          b++;
          timeCop += parseFloat(line[timeCanvas], 10);
          timeSop += parseFloat(line[timeSvg], 10);
      }
  }
  var ctx = document.getElementById("myChart").getContext("2d");
  var myNewChart = new Chart(ctx).Bar(data);
      var data = {
  labels : ["January","February","March","April","May","June","July"],
  datasets : [
    {
        fillColor : "rgba(220,220,220,0.5)",
        strokeColor : "rgba(220,220,220,1)",
        data : [65,59,90,81,56,55,40]
    },
    {
        fillColor : "rgba(151,187,205,0.5)",
        strokeColor : "rgba(151,187,205,1)",
        data : [28,48,40,19,96,27,100]
    }
]
}
  });
});

</script>
</head>

    <canvas id="myChart" width="400" height="400"></canvas>

</body>

First part of code works well and is used to get data from .csv file. I want to show arithmetic mean in bar graph so i wanted to use Chart.js but i get error on my browser:

Unhandled Error: Cannot convert 'data.labels' to object

Error comes from Char.js file-script, but it must be something with my bad implementation coz when i try to use it on blank page (with no other functions) there is no error and i see graph. What i do wrong??

Upvotes: 0

Views: 2497

Answers (1)

VitaliyG
VitaliyG

Reputation: 1857

You are declaring data after if was used for creating chart, try it in this order:

var data = {...}; //first initialize your data
var myNewChart = new Chart(ctx).Bar(data); //then use it

Upvotes: 1

Related Questions