Google Column Chart blank page - google-visualization

I am working on this project which I need to make a Google Chart (column chart) to make the data in my database visualize. I checked the IP and the database (the data comes from a database), everything works fine. But when I try to see the output on my computer, the page is blank. I thought the problem comes from google.load, and I made it like this below. I still get blank page. Please help me get this through. Thanks!
//
google.load('visualization', '1.0', {packages:['corechart'], callback: drawChart});
//
Here is the whole page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><html>
<head>
<title>R1 Google Chart</title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the column chart package.
// Set a callback to run when the Google Visualization API is loaded.
google.load('visualization', '1.0', {packages:['corechart'], callback: drawChart});
function drawChart() {
var jsonData = $.ajax({
url: "chart.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Solar Panel Data',
width: 800,
height: 600,
hAxis: {title: 'time', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the column chart-->
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>
PHP page
<?php
$con=mysql_connect("131.xxx.xxx.xx","xx","xxxx") or die("Failed to connect with database!!!!");
mysql_select_db("r1array", $con);
/** This example will display a column chart. If you need other charts such as a Bar chart, you will need to modify the code a little
to make it work with bar chart and other charts **/
$sth = mysql_query("SELECT UNIX_TIMESTAMP(TimeStamp), Pac FROM SolarData");
/*
---------------------------
example data: Table (Chart)
--------------------------
TimeStamp Pac
2013-08-16 06:45:01 0
2013-08-16 06:50:01 0
2013-08-16 06:55:01 12
2013-08-16 07:00:00 39
2013-08-16 07:05:01 64
2013-08-16 07:10:00 84
*/
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
array('label' => 'TimeStamp', 'type' => 'TIMESTAMP DEFAULT NOW()'),
array('label' => 'Pac', 'type' => 'INT')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
//
$temp[] = array('v' => (string) $r['TimeStamp']);
// Values of each slice
$temp[] = array('v' => (int) $r['Pac']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
mysql_close($db);
?>

It seems that prepare data in wrong way in your php file. With your html file and following php file which fake your data I got column chart.
<?php
/*
---------------------------
example data: Table (Chart)
--------------------------
TimeStamp Pac
2013-08-16 06:45:01 0
2013-08-16 06:50:01 0
2013-08-16 06:55:01 12
2013-08-16 07:00:00 39
2013-08-16 07:05:01 64
2013-08-16 07:10:00 84
*/
$table = array();
$table[0] = array('TimeStamp', 'Pac');
$table[1] = array('2013-08-16 06:45:01', 0);
$table[2] = array('2013-08-16 06:50:01', 0);
$table[3] = array('2013-08-16 06:55:01', 12);
$table[4] = array('2013-08-16 07:00:00', 39);
$table[5] = array('2013-08-16 07:05:01', 64);
$table[6] = array('2013-08-16 07:10:00', 84);
$jsonTable = json_encode($table);
echo $jsonTable;
?>
There is comment in your php file This example will display a pie chart.... Which chart do you want to create?

Off the bat, I can see a problem here:
$table['cols'] = array(
// Labels for your chart, these represent the column titles
array('label' => 'TimeStamp', 'type' => 'TIMESTAMP DEFAULT NOW()'),
array('label' => 'Pac', 'type' => 'INT')
);
as 'TIMESTAMP DEFAULT NOW()' and 'INT' are not valid data types for a DataTable. If you want to create Date objects from your timestamps, you need to use the 'date' or 'datetime' data type, and format your timestamps as strings with the format 'Date(year, month, day, hour, minute, second, millisecond)', where month is zero-indexed (so January is 0 not 1). The 'INT' type should be 'number'.
Update your code with these fixes. If your chart still doesn't work, view chart.php in a browser - you should see a JSON string output of your data (if not, there is a problem in your PHP that you will have to debug) - and update your post with this JSON string.

Related

Coldfusion refresh a field in a table output automatically

I have a table that outputs a bunch of records and has a status field that shows if the record has processed or not. I would like to auto refresh that one when the DB value changes from 0 to 1.
I would rather not refresh the whole table or page, but just that one field.
Any thoughts on how to accomplish this?
I'm sharing a working example solution that makes repeated AJAX jQuery calls to a simple CFML template. That CFML template returns a JSON object with data that is used to update the html table with jQuery. Here are the steps:
1. Step: Create a cfml file myTable.cfm that outputs a table with a cfml query data and binding each <tr> dom element with an identifier attribute to use as an dom element selector (e.g. <tr id=""dataID_#fruitsQuery.id#"">). This way you can manipulate/change the tables dom elements easier by accessing each table row and its children <td> with Javascript or Jquery. Please note my comments in the code:
myTable.cfm:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>myTable</title>
<!-- embed Bulma -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.3/css/bulma.min.css">
</head>
<body>
<cfscript>
// create a query and populate with random data
fruitsQuery = queryNew(
"id, fruit , price" , "numeric, varchar , numeric" ,
{
id: [1,2,3,4,5],
fruit: [ "Bananas" , "Kiwis", "Apples", "Oranges", "Peaches" ],
price: [ 1.99 , 0.99 , 2.99, 3.99, 6.99 ]
}
);
/**
* Ouptut the query data to a html table with bounded reference of the dom element to an ID
*/
// output table head
writeOutput("<table class=""table""><tr><thead><th>id</th><th>fruit</th><th>price</th></thead></tr><tbody>");
// output rows with data
cfloop( query="fruitsQuery" ){
// open table row and set an identifier with the data id for easier dom selection
writeOutput( "<tr id=""dataID_#fruitsQuery.id#"">" );
writeOutput( "<td class=""id"">#encodeForHTML( id )#</td>" );
writeOutput( "<td class=""fruit"">#encodeForHTML( fruit )#</td>" );
writeOutput( "<td class=""price"" >#encodeForHTML( price )#</td>" );
writeOutput( "</tr>" ); // close table row
};
writeOutput("</tbody></table>"); // close table
</cfscript>
<!-- embedded jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
// set a variable with function expressions
myTableLibary={
checkForUpdates: function(){
console.log('call invoked');
myTableLibary.myAjax( 'getLastUpdate.cfm' )
.done( function( result ) {
// set/reset all css for all table tds to default
$('td').css({'background-color':'','color':''})
// use the identifier ID as a selector and populate its child
// td.price with the data. Then set its css.
$('tr#dataID_'+ result.id + ' td.price' )
.css({'background-color':'blue','color':'white',})
.html( result.price );
// set css for td.fruit of the affected row
$('tr#dataID_'+ result.id + ' td.fruit' )
.css({'background-color':'yellow'})
})
.fail( function( e ) {
console.dir( e.responseText );
alert('Ops! Something went wrong!');
});
},
// function that returns an ajax object with Jquery (using deferred objects)
myAjax: function( url ) {
return $.ajax({
url: url,
type: 'GET',
processData: false,
contentType: false,
success: function( contentdata ){
return contentdata;
},
error: function( e ){
console.dir( e );
}
});
}
}
// onload: call the checkForUpdate function (ajax) every 2 seconds
window.setInterval(function(){
myTableLibary.checkForUpdates();
}, 2000 );
</script>
</body>
</html>
2. Step: Create a cfml template named getLastUpdate.cfm to return the data as JSON. This set of data is returned to the calling template as the JSON object named result (see it in the myTable.cfm), which is further used to populate the table price cell. Here is the code:
getLastUpdate.cfm
<cfscript>
// create the random data. I use bracket notation to make sure case is preserved in any CF engine version.
result={};
result["id"]=RandRange( 1, 5 );
result["price"]=RandRange( 1, 22 ) & "." & randRange (0, 99) ;
randomID=RandRange(0, 10 );
// reset the stream, add content type and output the data as JSON
cfcontent( reset = "true" );
cfheader( name="content-type", value="application/json");
writeoutput( serializeJSON( result ) );
</cfscript>
Step 3: Open the browser and call the myTable.cfm running witin your preferred cfml engine.
To see the action in your browsers background, watch the network tab in your preferred browsers dev tool and see all the available tabs with all informations.

Is it possible to highlight some states of US and some states of Canada in GeoChart?

Region 1
Region 2
I am trying to add map on a location page and I want to select some states from US and Canada in different regions when user hovers on a specific part of the map. Basically a map of North and South America(Brazil and Argentina) with different regions.
In the following code I attempted to highlight 2 US states and 1 Canada state. But I get "Requested map does not exist" error when I try to highlight states on a continent.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['geochart'],
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['State', 'Offices'],
['New Jersey', 2],
['Alabama', 3],
['Toronto', 1]
]);
var options = {
region: '019', // Americas Continent
colorAxis: {
colors: ['#00853f', 'black', '#e31b23']
},
backgroundColor: '#81d4fa',
datalessRegionColor: 'gray',
defaultColor: '#f5f5f5',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('geochart-colors'));
chart.draw(data, options);
};
</script>
</head>
<body>
<div id="geochart-colors" style="width: 100%; height: 100%;"></div>
</body>
</html>
Is it possible to do so? How can I achieve something like the image attached?
I would really appreciate your time and help. Thank you!

How to control haxis dataformat in google visualization chart?

I'm using the Google visualization chart in my application for drawing a line chart. It works great except one thing in the hAxis the entered number converts itself to thousands like below. I know this is happening because im trying to display huge numbers but still i would like to know if there is way to get around this?
Code
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Degree Level');
data.addColumn('number', 'Graduate or professional degree');
data.addColumn('number', "Bachelor's degree");
data.addColumn('number', "Associate's degree");
data.addColumn('number', "High school or vocational training");
data.addRows([
[2, 39758,93179, 78578,49141],
[3, 100747, 300646, 220982,100456],
[4, 49964, 68022, 21092,6943],
[5, 150370, 124868, 27120,8204]
]);
var options = {
chart: {
title: 'Education Report',
subtitle: 'distributed by experience'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="linechart_material"></div>
</body>
</html>
Output
Can someone let me know how can i make the hAxis to display in number?
There are two solutions to get the format that you want.
Either you use version 1 of the corecharts package :
so load the package like this :
// instead of : google.load('visualization', '1.1', {packages: ['line']});
google.load('visualization', '1', { packages: ['corechart'] });
and call your chart like this :
// instead of : var chart = new google.charts.Line(document.getElementById('linechart_material'));
var chart = new google.visualization.LineChart(document.getElementById('linechart_material'));
And you'll get what you want.
See a demo jsfiddle here.
Or alternatively,
Use version 1.1 of the package (you already do in your example) like this :
google.load('visualization', '1.1', {packages: ['line']});
and then specify in your chart options the vAxis format like this :
vAxis: { format: '###,###,###' },
and load the chart this way, so that the vAxis settings are taken into account :
chart.draw(data, google.charts.Line.convertOptions(options));
That'll work too.
See a demo jsfiddle here.
The problem here is that the way options are defined has changed from v.1 to v.1.1. So if you want to use the v.1.1 package you have to call google.charts.Line.convertOptions() for your options to be interpreted correctly.

Google Chart not showing info from google sheet unless sheet is accessed

I have a bunch of sheets that I'm using to store the marks of my students for a couple of my classes. On my website, I am using HTML and Google's Query Language to pull info from the sheets (2 columns...the students numbers of each student and their mark). If I've edited the spreadsheet on any given day, the chart shows up properly, but if I have not edited it that day then it shows incorrect values for their marks or old values for their marks. I think it's something to do with the sheets, but I can't be sure.
Here's the HTML code from my site:
<html>
<head>
<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 query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/ccc?key=14mPTcYYraMyuBnEFSJW74ZQ3xjWSSOuDqoxB2VrvAvw&tq=select%20D%2C%20E%20where%20D%3C%3E%22Avatar%22%20order%20by%20E%20desc%20label%20E%20%22Experience%20Points%22');
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.ColumnChart(document.getElementById('columnchart'));
var options = {'title':'Experience Points',
'width':'927',
'height':'510',
'chartArea': {'left':'50', 'width':'90%'},
legend: { position: 'top', maxLines: 2 },
hAxis: {showTextEvery: 1, slantedText: true, slantedTextAngle: 90, viewWindow:{max:33}},
bar:{groupWidth: '60%'},
isStacked: true};
chart.draw(data, options);
}
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<span id='columnchart'></span>
</body>
</html>
Any ideas? By the way, the sheet is set so that anyone on the internet can find and view.

Create clickable element in Google Visualization line chart

Is it possible to attach an onclick method to the elements within a Google Visualization line chart? For example, if a user clicks on point within the chart I want to send the user to a page with more details. I've gone all through the documentation and can't find an example of how to do this.
I see that there are methods for events (from the documentation) but with no clear example it's not making much sense.
Thanks!
You can do this using a 'select' event, which will be triggered each time a user clicks on a point on the line chart. I've included a working example below, including the redirect with a couple of values. The Google code playground has a nice example of how to use event handlers on a table - the same type of functionality can be used across most of the visualizations.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['barchart']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows(4);
data.setValue(0, 0, '2004');
data.setValue(0, 1, 1000);
data.setValue(0, 2, 400);
data.setValue(1, 0, '2005');
data.setValue(1, 1, 1170);
data.setValue(1, 2, 460);
data.setValue(2, 0, '2006');
data.setValue(2, 1, 660);
data.setValue(2, 2, 1120);
data.setValue(3, 0, '2007');
data.setValue(3, 1, 1030);
data.setValue(3, 2, 540);
chart = new google.visualization.LineChart(document.getElementById('visualization'));
chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
vAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
});
// a click handler which grabs some values then redirects the page
google.visualization.events.addListener(chart, 'select', function() {
// grab a few details before redirecting
var selection = chart.getSelection();
var row = selection[0].row;
var col = selection[0].column;
var year = data.getValue(row, 0);
location.href = 'http://www.google.com?row=' + row + '&col=' + col + '&year=' + year;
});
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body>
<div id="visualization" style="width: 600px; height: 400px;"></div>
</body>
</html>
getSelection().column is not working, it return an "unknown" value. The issue was posted in the Google Visualization API bug reports page.