Google Chart Shows Up Locally but not on Server - javascript

Whenever I run my app from the flask server locally on my own machine then my google chart shows up and looks great. However, when I log onto my own server and try running my app from there nothing show's up.
I have looked at the console and it does not show any errors and furthermore shows the space where the google chart should go but it is blank.
This is my code to create the chart. This is using the flask template inheritance model.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var course = '{{ myFun }}';
course = course.split(' ');
var putInTable = new Array();
for (var i = 0; i < course.length; i++){
putInTable.push(course[i].split(":"));
}
putInTable.pop();
for (var i = 0; i < putInTable.length; i++){
putInTable[i][1] = parseFloat(putInTable[i][1]);
}
putInTable.unshift(["courseName", "overlap"]);
var data = google.visualization.arrayToDataTable(putInTable);
var options = {title: "Visualization of Overlap"};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>

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);
}
...

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>

how to solve Google Charts loader.js can only be loaded once

<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var completed=parseInt(document.getElementById('completed1').value);
var notcompleted=parseInt(document.getElementById('notcompleted1').value);
alert(completed);
alert(notcompleted);
var data = google.visualization.arrayToDataTable([
['Task', 'Student'],
['Students Completed', completed],
['Students Not Completed', notcompleted],
]);
var options = {
title: ''
};
var chart = new google.visualization.PieChart(document.getElementById('piechart1'));
chart.draw(data, options);
}
</script>
this script is on my one page i am calling this page multiple times so in console it shows "Google Charts loader.js can only be loaded once."
Move it to whatever file you use to preload all your other global functions etc.
example, i have mine the app.js (using angular)

How to read data in json file in javascript to use it for google charts?

I have data in a path static/data.json.I am trying to plot chart using google charts.I want to take out data in data.json file and use it for google charts.
data.json is given below
data = '[{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v":0},]';
my html code is in template/isworked.html.
Below code is isworked.html
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="application/json" src="static/d.json"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var mydata = JSON.parse(data);
function drawChart() {
// Create the data table.
//loading data from json
var data = new google.visualization.DataTable();
data.addColumn('string', 'Feature');
data.addColumn('number', 'Positive');
var f,n;
for(var i = 0 ; i<data.length;i++){
f = data[i].k
n = data[i].v
data.addRows([[f,n]])
}
// Set chart options
var options = {'title':'Pie Chart',
'width':800,
'height':700};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
I am not able to plot graph.
This data.json is generated from a python script. I am running everyting using flask framework in Ubuntu
I have no experience in this topic. Can anybody help me?
UberKaeL is correct.
update:
corrected multiple problems with the code and data, e.g., the trailing comma in the data. It works now ... click the "Run Code Snippet" button.
"mydata" is the problem. You are attempting to use data before the json file has loaded. That triggers the error. And mydata is not used for anything. You also need to add a DIV to hold the pie chart. The code snippet below works, but the json data is incorrect for drawing a pie chart. Correct the data and it should work for you.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var mydata = [{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v": 0}];
</script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Feature');
data.addColumn('number', 'Positive');
var f,n;
for(var i = 0 ; i<mydata.length;i++){
f = mydata[i].k
n = mydata[i].v
data.addRows([[f,n]])
}
var options = {'title':'Pie Chart', 'width':800, 'height':700};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
After a while it seems like your page runs the code before loading the json file. Reading json like that is not a good practice, is better to do an AJAX request like jQuery.getJSON()
so if your are using jQuery do this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON</title>
</head>
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var mydata=jQuery.getJSON("static/d.json");
if(mydata) {
alert("yay worked");
}
else {
alert("something is wrong");
}
//rest of your code
//function drawChart() { ...
</script>
</body>
</html>
Also is a good practice to enclose your program inside a $(document).ready and remember to remove last comma in your JSON:
data = '[{"k": "RAM" , "v":0.515625},{"k": "Camera" , "v":0.515625},{"k": "Design" , "v":0.05},{"k": "Processor" , "v":0}]';
#Robert gives you a good answer about how to draw the chart
You are not using mydata where you put json read values.
data contains an empty new google.visualization.DataTable() and the loop are reading values from it, not from mydata.

Categories