Search code examples
javascriptjquerygoogle-visualizationjquery-csv

creating google chart from csv using js/jquery


Here is my code to create google chart from csv data. code look fine but still there is some error.

Code looks fine but error is may be due to some jquery syntext. I appreciate if someone can help me

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);

    function drawChart() {
       // grab the CSV
       $.get("Chart1-data.csv", function(csvString) {
          // transform the CSV string into a 2-dimensional array
          var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
        alert(arrayData);
          // this new DataTable object holds all the data
          var data = new google.visualization.arrayToDataTable(arrayData);

          // this view can select a subset of the data at a time
          var view = new google.visualization.DataView(data);
          view.setColumns([0,1]);

         // set chart options
         var options = {
        title: "A Chart from a CSV!",
        hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
        vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
        legend: 'none'
         };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));
        chart.draw(data, options);
});
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Chart1-data.csv

Category,

A,34

B,23

C,14

D,57

E,18    

Other,5

Error:

SyntaxError: missing ) after argument list

i.e. line where script ends

UPDATE: there was }); missing. Now no error but chart does not appear


Solution

  • Your closing brackets for $.get( should be }); not just };

    $.get({
     // code
    });
    

    And you're also missing a closing curly bracket to close your function.

    Demo