Gordon Mc Gordon Mc - 3 months ago 17
HTML Question

Google Chart is blank when I use json data

I have a crontab job that does daily updates to a file which then contains:


  • Date (year followed by month, both numeric)

  • Number of tests run in that month



I want to be able to display this information graphically on a webpage. It seems that Google Charts together with json should be able to do this, but so far I just get a blank page when I try this.

I don’t know if there is a standard way (tool or process) to debug problems with these tools – if there is, please edumacate me :-).  In the meantime, I have tried to narrow the problem down by breaking the task down into smaller component parts ; each seems fine on its own, but the combo does not work.

Here’s the html page that yields nothing at all: (Based largely on the example in https://developers.google.com/chart/interactive/docs/php_example)

<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var jsonData = $.ajax({
url: "/mypath/gtest_usage.json",
dataType: "json",
async: false
}).responseText;

// Create our data table out of JSON data loaded from data file.
var data = new google.visualization.DataTable(jsonData);
data.addColumn('date', 'Month');
data.addColumn('number', 'Tests per Month');

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {height: 600});
}

</script>
</head>

<body>
<!--Div that will hold the chart-->
<div id="chart_div"></div>
</body>
</html>


where the content of /mypath/gtest_usage.json is:

{
"cols":[
{"type":"datetime"},{"type":"number"}
],
"rows":[
{"c":[{"v":"Date(2015, 3)"},{"v":10}]},
{"c":[{"v":"Date(2015, 5)"},{"v":20}]},
{"c":[{"v":"Date(2015, 8)"},{"v":14}]},
{"c":[{"v":"Date(2016, 3)"},{"v":30}]},
{"c":[{"v":"Date(2016, 5)"},{"v":17}]}
]
}


The format for the json file above is based on e.g. sending JSON dates to google charts API from Perl

What I have tried, for narrowing the issue down:

Step 1: Don’t use a separate file with the json data – just hardcode it ; this DOES draw a chart, which suggests that the basic html file etc is OK and it’s just the external data that is somehow invalid or not matching my html file’s requirements:

var data = new google.visualization.DataTable();
data.addColumn('date', 'Month');
data.addColumn('number', 'Tests per Month');
data.addRows([
[ new Date (2015, 3), 10],
[ new Date (2015, 5), 20],
[ new Date (2015, 8), 14],
[ new Date (2016, 3), 30],
[ new Date (2016, 5), 17]
]);


Step 2: Check the validity of my json file’s syntax, using e.g. http://jsonlint.com/ - it says the syntax is fine.

Step 3: Vary how I define the column data. I’ve seen examples where e.g. the column data is not defined in the html file and comes only from the json file. Perhaps my column definitions in the html do not match the json definition, so I have tried:


  • remove the data addColumn lines in my html file and use only the json
    content

  • remove the cols definition in the json file and use only
    the content in the html file.



Neither of these made any difference – still blank.

Step 4: Based on other users’ experiences posted here on StackOverflow and elsewhere, I’ve checked for common mistakes in the json content such as mismatching the expected type vs the provided value for data (e.g. specifying it as a number but providing it in quotes so that it is a string).

I could be a long way away from having a valid solution here, or very close – and I can’t tell due to the lack of diagnostics, error messages etc. Do you guys see what is wrong with my approach ? Do you know of any mechanisms etc that can help a neophyte like myself get an actual error message or other such diagnostic that could help me see what I am doing wrong ?

Thanks in advance for any light you can shed on this.

Answer

the json data looks valid and works fine here, you may want to add column labels...

{"type":"datetime", "label": "Date"},{"type":"number", "label":"Amount"}

when using json to create the DataTable, don't need data.addColumn

see following working snippet...

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var jsonData = {
   "cols":[
     {"type":"datetime"},{"type":"number"}
    ],
   "rows":[
     {"c":[{"v":"Date(2015, 3)"},{"v":10}]},
     {"c":[{"v":"Date(2015, 5)"},{"v":20}]},
     {"c":[{"v":"Date(2015, 8)"},{"v":14}]},
     {"c":[{"v":"Date(2016, 3)"},{"v":30}]},
     {"c":[{"v":"Date(2016, 5)"},{"v":17}]}
   ]
  };
  var data = new google.visualization.DataTable(jsonData);
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {height: 600});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

EDIT

and recommend not using async: false

and use the success and error handlers, as follows...

function drawChart() {
  $.ajax({
    url: 'getdata.php',
    data: '/mypath/gtest_usage.json',
    dataType: 'json',
    success: function (jsonData) {
      var data = new google.visualization.DataTable(jsonData);
      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, {height: 600});
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log(errorThrown + ': ' + textStatus);
    }
  });
}
Comments