Reputation: 928
I'm new to SQL, JSON and Fusion Table. I want to get data from a Fusion Table and store it in a variable in javascript, so that I can append the data in a div element.
This is the javascript I got so far:
var TopCity;
TopCity = '{
"dataSourceUrl": 'http://www.google.com/fusiontables/gvizdata?tq=',
"query":
'SELECT Location FROM 131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V ORDER BY Total_Task_Num DESC LIMIT 1',
}';
$("#TopCityDiv").append("<div>" + TopCity + "</div>");
Basically, I want to find the city with the top number of completed tasks and display the city name.
I read through the fusion table sql stuff but am still confused: https://developers.google.com/fusiontables/docs/v1/sql-reference
Appreciate all help.
Update: It works!
In order to query my fusion table and not just save it in a table, I need to enable the Fusion Table API and make a public API key.
Working code:
$(document).ready(function() {
var TopCity;
$.ajax({
type: "GET",
url: "https://www.googleapis.com/fusiontables/v1/query?sql=SELECT+Location+FROM+131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V+ORDER+BY+Total_Task_Num+DESC+LIMIT+1&hdrs=false&typed=false&fields=rows&key={API Key}",
success: function(data) {
TopCity = data["rows"];
$("#TopCityDiv").append("<div>" + TopCity + "</div>");
},
error: function(xhr, error) {
console.log('NaN');
}
});
});
Upvotes: 0
Views: 339
Reputation: 431
You should use a callback to get the data. For example, you could use code like below
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var TopCity;
$.get('https://www.googleapis.com/fusiontables/v1/query?sql=SELECT Location FROM 131fgSFd-cumxvMzICckXO-W4CldzfO9J9D--Vw9V ORDER BY Total_Task_Num DESC LIMIT 1&key={your API key}', function (data, status, xhr) {
//assign the data to TopCity for future use
TopCity = data;
//do something with the data here
$.("#TopCityDiv").append("<div>" + data + "</div>");
});
});
</script>
Upvotes: 1