google visualization query can't run maximum and sum query - javascript

I'm trying to get the data from my fusion tables. when I use SELECT query the data show successfull. but when I'm using SUM and MAXIMUM query the firebug show error :
"SyntaxError: syntax error
Error 500 (There's a p"
when i test my query from fusion query the query works.
when i search based from firebug error, it's because i'm not specify the script tag to script type="text/javascript" .
but i think it's not actualy the error i get, because yesterday my code works. and today i don't know why my code doesn't works.
Can anybody help me? thanks for any help.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Fusion Table data ID
var FT_TableID = '1j1AG2s_IgNBQmm0QP9yYGHFg2_rNSZoEH4ee80In';
var FT_TableIDSP = '1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR';
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
function getKP() {
// set the query using the parameters
var FT_Query_KP = "SELECT 'Kelompok Penanam', count() FROM "+FT_TableID+" GROUP by 'Kelompok Penanam' ORDER by 'idPenanam'";
//var FT_Query_KP = "SELECT SUM('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR";
//var FT_Query_KP = "SELECT MAXIMUM('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR";
var queryText = encodeURIComponent(FT_Query_KP);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(KP);
}
// Set a callback to run when the Google Visualization API is loaded.
function KP(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var KPname = response.getDataTable().getValue(0,0);
document.getElementById('dropdownKP').innerHTML = KPname;
}
</script>
<script type="text/javascript">
getKP();
</script>
</head>
<body>
<div id="dropdownKP"></div>
</body>
</html>

We've identified a problem in the code for summaries with no second column in the projection; pie charts are the only ones that allow that, so it slipped past us. We are working on a fix and will update this question when it's available.
That said, the pie charts resulting from such queries wouldn't be too useful because they only have a single value.

Thanks Rod and Juvian, I change code from google visualization query to google fusion v1 query from this link

Related

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>

How to use AJAX to POST to PHP?

As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.
I found this answer and tried to follow it. This is my code right now (both in the same file)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getClientScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH)
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
<script type="text/javascript">
getScreenResolution();
</script>
</body>
</html>
<?php
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
if(isset($_POST['screenResolutionW'])) {
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH
."\r\n");
fclose($fh);
}
?>
However, this does not work.
I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.
Edit: My PHP and HMTL are in the same file (index.php).
Edit 2: Removed old code for clarity.
This results in these error messages:
Notice: Undefined index: screenResolutionW in index.php on line 153
Notice: Undefined index: screenResolutionH in index.php on line 154
What you want to do with $.post is include your data like this:
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.
You will also want to change your POST identifiers to be quoted:
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");
EDIT
Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:
EDIT TWO
Added an onload handler for the document:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
</body>
<script type="text/javascript">
$(function() {
getScreenResolution();
});
</script>
</html>
OTHER NOTES
You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.
Then once separated you should not run your PHP until you test for the existence of a variable, for example:
if(isset($_POST['screenResolutionW'])) {
// your code to write to the file here
}
EDIT THREE
I placed all of the JavaScript in the same script block in the head of the file and have tested again:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
getScreenResolution();
});
</script>
</head>
<body>
</body>
</html>
Here you can see the variables are being posted:
Adapting the others answers.
try it:
function getScreenResolution() {
"http://example.com/index.php", screenResolutionW + screenResolutionH
$.ajax({
url: '/index.php',
method: 'POST',
data: {
screenResolutionW : screen.width,
screenResolutionH : screen.height
},
success: function(data) { console.log(data); }
});
}
And in your PHP
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
echo $screenResolutionW . " - " . $screenResolutionH;
you have to use serialize the array before doing post request.
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
var serializedArr = {
width: screenResolutionW,
height: screenResolutionH
};
$.post('/index.php', serializedArr, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
In the server end, you will get values in $_POST variable.
Apart of all those mistakes you have discovered thanks to other replies, you have these:
$screenResoltuionW = ...
Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW
Same thing with $screenResoltuionH...
That's why you don't get any value in the file, because those variables doesn't exists.

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.

How to Convert Maxmind Geoip1 javascript script to Geoip2

Using the first Geoip I was using a simple Javascript code (as seen below), but I've been trying all day to figure out what I need to do to have the script recognise the country code for Maxmind Javascript Geoip2.
The Original GEOip code
<script type="text/javascript">
var user_country = geoip_country_code();
if(user_country == "US")
document.write(hockeyAds[4]);
else
document.write(hockeyAds[5]);
</script>
What I have in the new header
<script type="text/javascript" src="//j.maxmind.com/js/apis/geoip2/v2.0/geoip2.js"></script>
The latest code that I have attempted to use.
<script type="text/javascript">
var user_country = geoip2.cityISPOrg.country.iso_code();
if(user_country == "US")
document.write(hockeyAds[4]);
else
document.write(hockeyAds[5]);
</script>
Below on the same page I have tried this script that someone made and I was able to get it to type out the correct country code. So I am convinced that it is a problem with the above javascript code.
<script>
geoip2.cityISPOrg(function (response) {
$("#usercountry").html(response.country.iso_code);
});
</script>
<p>
<span id="usercountry"></span>
</p>
Not really all the great with understanding Javascript.
Thanks
You need to pass success and error callbacks to the geoip2 methods. Try this:
geoip2.country(
function (response) {
if (response.country.iso_code === "US") {
document.write(hockeyAds[4]);
} else {
document.write(hockeyAds[5]);
}
},
function (error) {
// handle error
}
);
Also, this tutorial might help you understand the API: http://dev.maxmind.com/geoip/geoip2/javascript/tutorial/

Dynamic pie chart in Google Chart is not working

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>

Categories