Google Charts Error 'Not An Array' on Ajax Update - javascript

I have a simple Google chart which renders fine with the following data on initial page load:
[['days','AA','BB'], ['270',15,15],['240',19,19],['210',23,23],['180',31,31],['150',34,34],['120',47,47],['90',57,57],['60',71,71],['30',81,81],['0',94,94]]
When I attempt to refresh it via an Ajax call which currently returns exactly the same data I get an error 'not an array'.
This is my initial function which draws the chart correctly:
<script type="text/javascript">
var chart;
var options;
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataArray = ${initialChartData};
var data = google.visualization.arrayToDataTable(dataArray);
options = {
chart: {
title: 'Bookings by Days Before Holiday Start Date',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, options);
}
</script>
My Ajax Handler:
$('#dataAnalysisForm').ajaxForm({
success : function(responseText) {
//error here as responseText 'is not an array'
//it is the same String returned via Ajax as was
//used to render the initial chart
//the initial data was written to the page server side.
var data = google.visualization.arrayToDataTable(responseText);
chart.draw(data, options);
}
});
What needs to change in the above code to make this work on initial page load and update correctly on Ajax response?

Just do this again:
var chart = new google.visualization.Bar(document.getElementById('columnchart_material'));
chart.draw(data, options);
If your data is already in the right format there is no need to convert it, so you can use chart.draw(responseText, options)

Related

Fetching data from spreadsheet in script: "Data table is not defined"

I’m trying to make a script using the Google Visualization App Geomap. In the example code on the Google Developers page, they are using a hard coded table. What I want to do, is to make code use data from a Google Spreadsheet connected to a Google Form. More specifically, I want to use the data of the spreadsheet tab «countries» from the following spreadsheet: https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit?usp=sharing.
Somehow this does not work, and I get the error messages listed below.
How can I collect the data from the spreadsheet in the right format? I have attempted to use this procedure to collect the data from the spreadsheet: https://google-developers.appspot.com/chart/interactive/docs/spreadsheets.
Error message on web page:
"Data table is not defined"
Error message in Safari Console:
TypeError: undefined is not an object (evaluating 'new google.visualization.Query’)
drawChart help:113
(anonymous function) help:117
My code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geomap"]});
google.setOnLoadCallback(drawMap);
function drawMap() {
var opts = {sendMethod: 'auto'};
// ***My code***
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit#gid=957991050', 'sheet=countries', 'headers=1');
var data = query.send(handleQueryResponse);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
return response.getDataTable();
}
</script>
Hope there is someone out there who can help me with this (hopefully) not so hard task. Thank you very much in advance! :-)
You can get data inside of a callback function handleQueryResponse
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
} else {
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
var data = response.getDataTable();
geomap.draw(data, options);
}
}
Google provides example here.
Also check format which you get in response and use method google.visualization.arrayToDataTable to format data as in example if needed cause it format should be correct.

Google Charts - number/string issue on hAxis (Jquery ajax JSON data)

What I want to do
I am trying to show data from a MySQL database in a "ComboChart" using Google Charts. In order to do that I followed this tutorial, made some alterations and came up with the code as shown on the very bottom of this post.
Actual behavior
The data displays correctly. I do have to tell Google Charts however that the "year" is a number what throws it into continuous "mode". That leads to the year on the hAxis displaying with decimal places, in particular if I don't have data for all consecutive years. (i.e. 2,010.5)
Desired behavior
I want Google Charts to display the year as if it was a string and operate in discrete "mode".
What I think the problem is
I think the problem, I am encountering is mostly due to the fact that the year (to be shown on the hAxis) is a int(11) in the database and that the json that is provided by a controller also has the year as a number. To clarify below an example of what the json could look like:
[
{
"year_data": 2010,
"data_1": 125895,
"data_2": 25158.5
}
]
As I use the controller for a bunch of other stuff, I would preferably not make any alterations to it.
What I tried to fix it
I tried the bold move of just changing data.addColumn('number', 'year_data'); to data.addColumn('string', 'year_data');. It didn't work and I got a "type mismatch".
I tried to come up with a workaround mostly involving hAxis.showTextEvery: and some sort of row count. It didn't work but that might very well be due to my lack of experience/knowledge.
The question in one sentence
How can I turn the year data into a string in JavaScript or having Google Charts behave as if it was a string?
Code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script src="/googlecharts/ajaxGetPost.js" type="text/javascript"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
function charts(data, ChartType) {
var jsonData = data;
google.load("visualization", "1", {
packages: ["corechart"],
callback: drawVisualization
});
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'year_data');
data.addColumn('number', 'Data 1');
data.addColumn('number', 'Data 2');
$.each(jsonData, function(i, jsonData) {
var year = jsonData.year_data;
var data1 = jsonData.data_1;
var data2 = jsonData.data_2;
data.addRows([
[year, data1, data2]
]);
});
var options = {
colorAxis: {
colors: ['#54C492', '#cc0000']
},
datalessRegionColor: '#dedede',
defaultColor: '#dedede',
legend: {
position: 'bottom',
alignment: 'start'
},
seriesType: 'bars',
series: {
1: {
type: 'line'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
$(document).ready(function() {
url = '/data/get';
ajax_data('GET', url, function(data) {
charts(data)
});
});
</script>
toString should work just fine, see following snippet...
var data = new google.visualization.DataTable();
data.addColumn('string', 'year_data');
data.addColumn('number', 'Data 1');
data.addColumn('number', 'Data 2');
$.each(jsonData, function(i, jsonData) {
var year = jsonData.year_data.toString();
var data1 = jsonData.data_1;
var data2 = jsonData.data_2;
data.addRows([
[year, data1, data2]
]);
});

Googlecharts - Annotation Chart - First column must contain date or date time

I'm trying to plot an annotation chart with google chart. However, I get the error "First column must be date or datetime". If I were to change the chart type to be area or line for example, it works fine.
Here's the javascript section of the "View page source" content of the final HTML page on which I'm expecting a graph to be drawn
<script type="text/javascript">
google.load('visualization', '1', {'packages':['annotationchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded FROM server.
var data_1 = google.visualization.arrayToDataTable([['ACTIVITY DATE TIME','ACTIVITY DURATION'],['2015-10-31 02:00:00',503],['2015-11-01 09:26:00',4],['2015-11-01 11:30:00',2],['2015-11-01 19:33:00',2],['2015-11-02 01:15:00',2],['2015-11-02 03:09:00',2],['2015-11-02 07:04:00',2],['2015-11-02 09:47:00',2],['2015-11-02 11:10:00',2]]);
var options = {
displayAnnotations: true
};
var chart_1 = new google.visualization.AnnotationChart(document.getElementById('plot1'));
chart_1.draw(data_1, options);
}
;
</script>
Could I request help please to figure out the problem? Is there any typecasting needed or anything whatsoever to get this working please?
UPDATED CODE
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['annotationchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded FROM server.
var data_1 = google.visualization.arrayToDataTable([<?php echo (implode(",", $chart_array_1)); ?>]);
var options = {
displayAnnotations: true
};
var chart_1 = new google.visualization.AnnotationChart(document.getElementById('plot1'));
chart_1.draw(data_1, options);
}
;
Yes, you have to cast those strings as Dates.
var data = [
['ACTIVITY DATE TIME', 'ACTIVITY DURATION'],
['2015-10-31 02:00:00', 503],
['2015-11-01 09:26:00', 4],
['2015-11-01 11:30:00', 2],
['2015-11-01 19:33:00', 2],
['2015-11-02 01:15:00', 2],
['2015-11-02 03:09:00', 2],
['2015-11-02 07:04:00', 2],
['2015-11-02 09:47:00', 2],
['2015-11-02 11:10:00', 2]
];
// or var data = [<?php echo (implode(",", $chart_array_1)); ?>]
for(var i = 1; i < data.length; i++)
data[i][0] = new Date(data[i][0]); // converting strings to Dates
google.load('visualization', '1', {
'packages': ['annotationchart']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded FROM server.
var data_1 = google.visualization.arrayToDataTable(data);
var options = {
displayAnnotations: true
};
var chart_1 = new google.visualization.AnnotationChart(document.getElementById('plot1'));
chart_1.draw(data_1, options);
};
JSFiddle

Google Charts Api - Select specific column to draw

I'm working with Google Charts Api.
As a data surce, I'm using a Google spreeadsheat. I using this spreadsheat:
https://docs.google.com/spreadsheet/pub?key=0Amf7cOIp81pxdGdxUmFMZVVFVjBwTENTcUpVVldVRnc&output=html
The problem is that as the table has multiple columns, how can I select which column I wnat to show in the chart?
I get the table via: var data = response.getDataTable(); But I don't know hot to get some column from data.
In draw() method I don't know too if I can pass as parameter some specific column
Here my complete code:
google.load('visualization', '1.0', {'packages':['corechart']});
google.load('visualization', '1.0', {'packages':['controls']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/pub?key=0Amf7cOIp81pxdGdxUmFMZVVFVjBwTENTcUpVVldVRnc&output=html');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
// Testing
console.log(data.getColumnId(1));
var chart = new google.visualization.PieChart(document.getElementById('columnchart'));
var options = {'title':'World Cup Statistics',
'width':800,
'height':800};
chart.draw(data, options);
Use the setQuery method of the Query object:
query.setQuery('select A, B, C');
Use the letter ID's of the columns you want to select in the query. Documentation on the query language is here.

Google Visualization-Invalid row type for row 0

I have to visualize url json data on a pie chart with google visualization. My code seems to be as it has to be for the purpose, but I am getting an 'Invalid row type for row 0' error in the console. Is there any problem with the format of the data? If there is anyone that could help, that would be much appreciated. Here is my code:
PHP:
<?php
$json = file_get_contents('http://data.police.uk/api/crimes-street/all-crime?lat=52.629729&lng=-1.131592&date=2013-01');
$json = str_replace("\xe2\x80\xa8", '\\u2028', $json);
$json = str_replace("\xe2\x80\xa9", '\\u2029', $json);
echo $json;
?>
JavaScript:
<script type="text/javascript" src="https://www.google.com/jsapi"></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.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
//Create an array of the JSON data and then create our data table out of JSON data loaded from server.
var array = JSON.parse(jsonData);
var dataTableData = new google.visualization.arrayToDataTable(array);
var table = google.visualization.DataTable(dataTableData);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
Thank you.
The JSON does not represent data which can be transformed to a 2-dimensional array google.visualization.DataTable can simply not interpret this. Each item contains complex subitems like location and outcome_status.
You must include columns - arrayToDataTable is very specific about that.
The most important : How on earth do you imagine those data to be presented as a piechart? There is only one specfic number-field at first level, location_subtype. You cannot produce a piechart based on various strings.
But, you can sanitize the data and show them as a google.visualization.Table :
First create a DataTable with some columns :
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string','category');
dataTable.addColumn('string','context');
dataTable.addColumn('string','id');
dataTable.addColumn('number','location_subtype');
dataTable.addColumn('string','location_type');
dataTable.addColumn('string','month');
dataTable.addColumn('string','persistent_id');
convert your jsonData to JSON
var json=JSON.parse(jsonData);
sanitize and insert the data. Here I just delete the location and outcome_status subitems, but you may want to extract values from those subitems instead and insert them as columns in the dataTable :
for (var i=0;i<json.length;i++) {
delete json[i].location;
delete json[i].outcome_status;
var row = [];
for (var item in json[i]) {
row.push(json[i][item]);
}
dataTable.addRow(row);
}
finally create the Table() :
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(dataTable, {width: 1000, height: 300});
the result will look like this :
update
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string','category');
dataTable.addColumn('string','context');
dataTable.addColumn('number','id');
dataTable.addColumn('string','location_subtype');
dataTable.addColumn('string','location_type');
dataTable.addColumn('string','month');
dataTable.addColumn('string','persistent_id');
dataTable.addColumn('string','street name');
dataTable.addColumn('string','outcome status');
json=JSON.parse(jsonData);
for (var i=0;i<json.length;i++) {
var row = [];
row.push(json[i].category);
row.push(json[i].context);
row.push(json[i].id);
row.push(json[i].location_subtype);
row.push(json[i].location_type);
row.push(json[i].month);
row.push(json[i].persistent_id);
row.push(json[i].location.street.name);
row.push(json[i].outcome_status ? json[i].outcome_status.category : "null");
dataTable.addRow(row);
}

Categories