I am working on a UI where a user chooses both a start and end dates in order to retrieve data. Some of these data are shown in tables and I want to show a google chart related to those data displayed.
When the user finally chooses the dates, i send these two variables by using the $.post() function as follows:
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
$('#button-send').click(function() {
var url_route = "{{URL::action('Controller#general_stats_post')}}";
var start_date=$('#start_date_i').val();
var end_date=$('#end_date_i').val();
var datos = {start_date: start_date, end_date:end_date,_token:_token};
Once the send button is clicked, i use the $.post() function which works fine:
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*Here goes the google chart*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
The events_types string is, for example:
[['Event','Total'],['Workshop',1],['Seminar',1]]
which perfectly works in google's jsfiddles.
So, what i have been trying is to put the google chart's drawChart() function inside the {} where the string events_types does exist as follows:
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*GOOGLE CHART*/
google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(response.events_types);
var options = {
title: 'My test'
};
var chart = new google.visualization.PieChart(document.getElementById('eventos_charts'));
chart.draw(data, options);
}
/*END OF GOOGLE CHART PART*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
I have put a console.log message to let me know that the drawChart() has been run. However, I never get that message. So this means the drawChart() function is never run :/ I am stuck.
Almost working - EDIT
This is the code that is working... but only if I define the data string manually, that is to say:
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable([['Evento','Cantidad'],['Taller',1],['Seminario',1]]);//DEFINED MANUALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to #FABRICATOR
/**** END Google charts: Events types *********/
}
However, if i tried to get the data dynamically:
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(the_string);//DEFINED DYNAMICALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to #FABRICATOR
/**** END Google charts: Events types *********/
}
I get the following error:
Uncaught Error: Not an array
Any ideas to make it work? What am I missing?
Finally I have found the easiest solution.
Given that I am using Laravel's ORM (Illuminate/Database), the gotten data comes in json format.
This works for Laravel and Slim framework.
So I pass the variables directly to the view (in Slim):
$app->render('home.php',[
'myArray'=>$myArray
]);
Then, inside the view (in this case, Twig view. It should be similar in blade), I get the array and put it in a variable inside the Javascript code:
var myArray = {{ myArray|json_encode|raw }};
Then I iterate to get each element and add it into the Google chart data array:
$.each(myArray,function(index, value){
//console.log('My array has at position ' + index + ', this value: ' + value.r1);
data.addRow([value.col1,value.col2,value.col3,value.col4]);
});
And it works now.
Related
It is fully functional. I want to check all the data. Using this, I can't see all the data.
alert("SHOW FORM DATA");
alert(PreparedFormObj());
FORM DATA
var PreparedFormObj = function () {
var _FormData = new FormData()
_FormData.append('Id', $("#Id").val())
_FormData.append('CreatedDate', $("#CreatedDate").val())
_FormData.append('CreatedBy', $("#CreatedBy").val())
_FormData.append('ProductId', $("#ProductId").val())
_FormData.append('ProductModelNo', $("#ProductModelNo").val())
_FormData.append('Name', $("#Name").val())
return _FormData;
}
SAVE DATA
var SaveProduct = function () {
alert("SHOW FORM DATA");
alert(PreparedFormObj());
}
for example convert to json
alert(JSON.stringify(Object.fromEntries(PreparedFormObj())));
I have some data in a Google Spreadsheet, which I'm pulling with Tabletop.js. I'm able to display my data as well in my showInfo() function. All good.
Now I try to achieve to display this data in a default Google Chart. In this case I use their map package to display my data on a map. They provided me some sample code, see here.
At the moment I'm struggling with the following function, whole code in my Fiddle:
mapdata.addRows([
// PREFERRED DATA TO COLLECT:
// [data.geoloc, data.GM_NAAM, 'blue' ],
// THE HARDCODED WAY:
['Kerkbrink 2 ANLOO', 'ANLOO', 'green'],
['Grote Kerkstraat 32 WIJK EN AALBURG', 'WIJK EN AALBURG', 'blue']
]);
How do I approach? I managed to display all data with a forEach in the showInfo function, but this does not work in this array.
I'm pretty new in JS-land, so I appreciate every help on achieving this.
Thanks in advance!
please find the updated fiddle here
is this what you are looking for ?
updated js code:
/* 1: tabletop shizzle */
var publicSpreadsheetUrl = 'https://docs.google.com/spreadsheets/d/1cpSdKrQK0DfRoC9_xgmAqwVaDqw8BKMOL7drA_QFIn0/edit?usp=sharing';
function init() {
Tabletop.init( { key: publicSpreadsheetUrl,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(data, tabletop) {
alert('Successfully processed!')
var chartdiv = document.querySelector(".chart_div");
console.log("data: ", data);
data.forEach( function(data) {
// card
var card = document.createElement('div');
card.classList.add("card");
//content
var content = document.createElement('div');
content.classList.add('content');
content.innerHTML = data.GM_NAAM + ' ' + data.geoloc;
// append
chartdiv.appendChild(card);
card.appendChild(content);
});
// trigger the google charts drapMap function and send the data to it
drawMap(data);
}
window.addEventListener('DOMContentLoaded', init);
/* 2: google chart shizzle */
google.charts.load('current', {
'packages': ['map'],
// DEFAULT GOOGLE API KEY
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawMap);
function drawMap(data) {
var mapdata = new google.visualization.DataTable();
mapdata.addColumn('string', 'Address');
mapdata.addColumn('string', 'Location');
mapdata.addColumn('string', 'Marker')
console.log(data);
data = data ? data : [];
var rows = [];
data.forEach(function(item){
rows.push([item.GM_NAAM, item.geoloc, 'green'])
})
// THIS IS THE PART I NEED THE DATA.
mapdata.addRows(rows);
// SOME OPTIONS
var url = 'https://icons.iconarchive.com/icons/icons-land/vista-map-markers/48/';
var options = {
zoomLevel: 7,
showTooltip: true,
showInfoWindow: true,
useMapTypeControl: true,
icons: {
blue: {
normal: url + 'Map-Marker-Ball-Azure-icon.png',
selected: url + 'Map-Marker-Ball-Right-Azure-icon.png'
},
green: {
normal: url + 'Map-Marker-Push-Pin-1-Chartreuse-icon.png',
selected: url + 'Map-Marker-Push-Pin-1-Right-Chartreuse-icon.png'
}
}
};
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(mapdata, options);
}
I have 3 html files that will use same variable,same function in javascript except query function.
Each html will query the data from different google sheet.
now I'm using script inside html like this
<script>
google.charts.load('current', {packages: ['geochart']});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1RsugJPtz2EdHOLaiL0SvR9bh61H-vAgn9x1QBjIJ--c/edit?usp=sharing');
query.send(handleQueryResponseTR);
}
function handleQueryResponseTR(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
chart.draw(view,options);
</script>
but I want to create external script file for all 3 html files because it use almost all the same variable/function.
the thing is, how can I do that with different data in query function?
Can I set new value(spreadsheet link) to query variable from external script in each html file?
anyone can help?
any example would be appreciated, thanks
I want my page to display a chart in google site, the datasource i used is google spreadsheet. I test my code and it works well in JSFiddle. But when i copy my code to Google Apps Script, it fail with ReferenceError: "google" is not defined. I have no idea about it, I don't know what should be added ot use google.visualization API, maybe Google Apps Script doesn't support google.visualization API? I just add function doGet(), You can see my code:
function doGet() {
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/a/valeo.com/spreadsheets/d/1wMku94s8LsbwPdoaVsJNL5IPdKVUdv8ZC_jgo2suV4Q/edit#gid=1287756093');
query.setQuery('select A, C');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
title: 'MS Project Licence From 2014',
hAxis: {title: 'Month',titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data, options);
}
}
Appreciated for any suggestion
I'm trying to dynamically render a google visualization chart with an AJAX call in flask to set the data. User enters input then clicks a link which calls the ajax function to get the data. the "/ajax_test" view will return a json object but the problem I have is i don't know how to correctly pass the data back into the DataTable function. How do i pass the json data i'm getting from ajax to a variable for the drawchart function?
Chart function:
<script type="text/javascript">
function drawChart(){
var data = new google.visualization.DataTable(jsondata);
var options = {
explorer: {},
}; //end options
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Ajax function:
<script type=text/javascript>
$(function() {
$('a#DrawChart').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/ajax_test',
{//input data sent to view}
, function(data) {
var jsondata = data.test_json;
drawChart();
});
return false;
});
});
</script>
This method doesn't know where jsondata comes from:
function drawChart() {
var data = new google.visualization.DataTable(jsondata);
...
}
Add jsondata as a parameter:
function drawChart(jsondata) {
var data = new google.visualization.DataTable(jsondata);
...
}
And then in your Ajax call pass jsondata to the method:
function(data) {
var jsondata = data.test_json;
drawChart(jsondata);
}
I have done something similar using the following code, this is a jinja2 example, so you have do adapt your code (change the way jsonData var is initialized):
<script type="text/javascript">
//load the Google Visualization API and the chart
google.load('visualization', '1', {'packages': ['corechart']});
google.setOnLoadCallback (createChart);
var jsonData = {{ value_columns | tojson | safe }}
function createChart() {
var dataTable = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//define options for visualization
var options = {is3D: 'no', title: 'Some Title' };
attachRedrawForTab(chart, dataTable, options);
attachRedrawForAccord(chart, dataTable, options);
//draw our chart
chart.draw(dataTable, options);
}
</script>