Dynamic pie chart in Google Chart is not working - javascript

I am new to Google Chart and I am trying create a dynamic pie chart in the dynamic webproject(Java EE). I have read the tutorial (https://developers.google.com/chart/interactive/docs/queries) and copy the pie chart code in the google code play ground.
function initialize()
{
// Replace the data source URL on next line with your data source URL.
// Specify that we want to use the XmlHttpRequest object to make the query.
var opts = {sendMethod: 'xhr'};
var query = new google.visualization.Query('https://docs.google.com/spreadsheet/tq?range=A%3AB&key=0Aq4N8GK8re42dHlGMG0wM00tdE5PVjJZellXTEhFNEE&gid=0&headers=-1', opts);
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response)
{
if (response.isError())
{
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true});
}
google.setOnLoadCallback(drawVisualization);
But it is not working and there is no piechart. Could please tell me where is the problem. My spreadsheet is https://docs.google.com/spreadsheet/ccc?key=0Aq4N8GK8re42dHlGMG0wM00tdE5PVjJZellXTEhFNEE
Thank you.

For some reason it sends the OPTION request instead of the correct GET. It is because you use the opts parameter, remove it and everything will work fine.
Also you can find a note about this parameter here:
https://developers.google.com/chart/interactive/docs/reference#Query
opt_options
[Optional, Object] A map of options for the request. Note: If you are accessing a restricted data source, you should not use this parameter.
Here is the full code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(initialize);
function initialize() {
// removed the `var opts...` line
var query = new google.visualization.Query('https://docs.google.com/spreadsheet/tq?range=A%3AB&key=0Aq4N8GK8re42dHlGMG0wM00tdE5PVjJZellXTEhFNEE&gid=0&headers=-1');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>

Related

Google App Script code to create a pie chart from spreadsheet data not showing up

It is just a simple script project that is supposed to create a pie chart from the data in a spreadsheet. I had it working when I built the DataTable within the HTML file, but I tried to adjust it with a query in order to pull the data from a spreadsheet and make the dashboard dynamic with changes to the spreadsheet.
Whenever I deploy it however, it just shows up as a blank screen. Any help/thoughts is appreciated! I will get it eventually...
HTML File Code:
<html>
<head>
<!--Load the AJAX API-->
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function initialize() {
var opts = {sendMethod: 'auto'};
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1BiNoiV10xrAU8PwdJfgldneLwFuCnY5GhQRDEIzftd8/edit#gid=0', opts);
}
// Send the query with a callback function.
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
//enter alert on user screen when clicking on section of chart
function selectHandler() {
var selectedItem = chart.getSelection()[0];
var value = data.getValue(selectedItem.row, 0);
alert('The user selected ' + value);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:400; height:300"></div>
</body>
</html>
JS File Code:
function doGet() {
return HtmlService.createHtmlOutputFromFile('webappchartv2');
}
Missing query.send(handleQueryResponse);
setOnLoadCallback is not set properly
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var opts = {sendMethod: 'auto'};
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1BiNoiV10xrAU8PwdJfgldneLwFuCnY5GhQRDEIzftd8/edit#gid=0', opts);
query.send(handleQueryResponse);
}
...

I am trying to create a google column chart from a google spreadsheet but keep getting blank

My code snip keeps giving me blank, not sure why. I included my spreadsheet link in the code which is shared with anyone with link, it's a range containing data of dates and stock price close values. if you can spot and fix the issue it will be great as I plan to reuse this code snip it for line charts too. Please indicate what I am missing anything. " I know its noob question but I am new to coding.
<!DOCTYPE html>
<html>
<head>
<title>Bar Chart with Dropdown JSON</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="div_chart"></div>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var queryString = encodeURIComponent('SELECT A3:B25');
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1DOq0dwcWN09MA-ScFbUF-Abl0OKzfqthx_ixpxIq7P0/edit#gid=59852832'+ queryString);
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, { height: 400 });
}
</script>
</body>`enter code here`
</html>

Why is my google chart javascript not doing anything?

In my home.scala.html page's head I have a comprehensive javascript to call a google chart, using a map passed from scala using the java play framework.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'xVariable');
data.addColumn('number', 'yVariable');
var mapVariable = #mapFromScala;
console.log("Hello world");
for (var mapKey in mapVariable) {
data.addRows([
[new Date(mapKey) , mapVariable[mapKey]]
]);
}
var options = {
chart: {
title: 'This is my map',
subtitle: 'it has a subtitle'
},
width: 1000,
height: 600
};
var chart = new google.charts.Line(document.getElementById('chartId'));
chart.draw(data, options);
}
</script>
and in body
<div id="chartId"></div>
Why don't I get anything back? Even the 'Hello world' console.log doesn't seem to show in SBT console.
The map variable must be brought in as a String. JSON can be used for this but
var mapVariable = "#mapFromScala"
Also works, although the process to convert from String back into a Map is inelegant.
This process is described here, except the data types are different and
data.addRows([[xVariable, yVariable]])
is invoked instead of
jsArray.xVariable = yVariable;

Integrate google chart in Laravel5.0 with the data from mysql database

I want to integrate google chart in my laravel5.0 application. The data is in mysql database. As far I've done researching over internet is given bellow
controller part
public function index(){
$barChart= DB::table('clients')
->select('clients.ClientName','clients.Price')
->get();
$bar = json_encode($barChart);
return view('home')
->with('bar', $bar);
}
If I print $bar , the result is
[{"ClientName":"nayeem","Price":1000},{"ClientName":"Tusher","Price":1000},
{"ClientName":"Nirjon","Price":1000},{"ClientName":"Remon","Price":1000},
{"ClientName":"Navid","Price":1000},{"ClientName":"Erfan","Price":1000},
{"ClientName":"Sazzad","Price":1000},{"ClientName":"Farin","Price":2000},
{"ClientName":"Arman","Price":1000},{"ClientName":"Sohan","Price":1000},
{"ClientName":"romi vai","Price":9000},{"ClientName":"tasif","Price":1000},
{"ClientName":"trina","Price":1000},{"ClientName":"Nuru Vai","Price":1000}]
view part
<div class="panel-body" id="barChart"> </div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$bar?>);
var options = {
title: 'My Bar chart',
is3D: 'true'
};
var chart = new google.visualization.PieChart(document.getElementById('barChart'));
chart.draw(data, options);
}
But it shows "table has no column" . I know I haven't create any column and I also understand that simply writing this google.visualization.DataTable(<?=$bar?>) will not create any column. I've tried many ways to create column but can not find any solution. How can I create data table from this?
I also tried chartWraper
<script type="text/javascript">
google.load('visualization', '1.0');
function drawInventoryChart() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [], //don't know how to put $bar here
option: {title: 'test'}
});
wrapper.draw('barChart');
}
google.setOnLoadCallback(drawInventoryChart);
</script>
This also does not work as I can not properly have the value of dataTable[] .
you can use array.forEach to load the data into the data table.
see following example...
google.charts.load('current', {
callback: function () {
// use the following
//var sqlData = <?=$bar?>;
// for example
var sqlData = [
{"ClientName":"nayeem","Price":1000},{"ClientName":"Tusher","Price":1000},
{"ClientName":"Nirjon","Price":1000},{"ClientName":"Remon","Price":1000},
{"ClientName":"Navid","Price":1000},{"ClientName":"Erfan","Price":1000},
{"ClientName":"Sazzad","Price":1000},{"ClientName":"Farin","Price":2000},
{"ClientName":"Arman","Price":1000},{"ClientName":"Sohan","Price":1000},
{"ClientName":"romi vai","Price":9000},{"ClientName":"tasif","Price":1000},
{"ClientName":"trina","Price":1000},{"ClientName":"Nuru Vai","Price":1000}
];
// create data table
var data = new google.visualization.DataTable();
data.addColumn('string', 'Client');
data.addColumn('number', 'Price');
// load data table
sqlData.forEach(function(row) {
data.addRow([row.ClientName, row.Price]);
});
var chart = new google.visualization.BarChart(document.getElementById('barChart'));
chart.draw(data, {
title: 'My Bar chart',
is3D: 'true'
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barChart"></div>

Creating Dashboard Using External Data (Google Spreadsheet) - JavaScript

Hey guys i am finding it hard to understand how the google visualization java script works as i am new to it. However i did have a crack at it following the documentations that have and managed to created a simple chart displaying the data from the a spreadsheet.
Now however i have been trying to implement added interactivity such as a slider to my chart and also a pie chart, just for testing sake and seeing if i can get it to work with my data.
My problem however to put it simply is that it does not work, nothing shows on the webpage and i have made sure i have linked the JS file correctly to my HTML file.
google.load('visualization', '1.0', {'packages':['controls']});
google.setOnLoadCallback(drawDashboard);
function drawDashboard() {
var query = new google.visualization.Query(
'//docs.google.com/spreadsheets/d/1FOVmfesx7ATNe8qjWjkU2GbjBCBZxL0BRswJv6rcGPs/gviz/tq?gid=1324373577&tq=select%20B,C%20where%20B%20%3C%3E%20%22%22');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
}
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
// Create a range slider, passing some options
var donutRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Number Attended'
}
});
// Create a pie chart, passing some options
var pieChart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart_div',
'options': {
'width': 300,
'height': 300,
'pieSliceText': 'value',
'legend': 'right'
}
});
// Establish dependencies, declaring that 'filter' drives 'pieChart',
// so that the pie chart will only display entries that are let through
// given the chosen slider range.
dashboard.bind(donutRangeSlider, pieChart);
// Draw the dashboard.
dashboard.draw(data);
You can't use google.visualization.Dashboard until it has been loaded.
Here is a simplified version to demonstrate.
google.load('visualization', '1.0', {
'packages': ['controls']
});
google.setOnLoadCallback(function() {
$("#out").text($("#out").text() + "google.visualization is " + google.visualization + " in the callback.\n");
});
$("#out").text($("#out").text() + "google.visualization is " + google.visualization + " out here.\n");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<pre id="out"></pre>
You need to re-factor your code so it doesn't try to use google.visualization until it has been loaded.

Categories