ReferenceError: "google" is not defined for Google Apps Script - javascript

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

Related

using external javascript with html and change specific variable?

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

Google Apps Script urlfetch causing error 500 when called via google.script.run

I am working on a bit larger project part of which is where custom formulas are to be designed, that fetch information related to an ASIN (Amazon Context) from ScanPower.com through urlFetch method of UrlFetchApp in Google Apps script.
The problem is, when I use those custom formulas in spreadsheet as normal spreadsheet function, it works fine and fetch data. If I call it through the menu item, it is still ok.
Now, using the sidebar html having a button to call the same function, the urlFetch used inside the function gives 500 error. This function is being called via the google.script.run.. The same error happens when I try to run it in debug mode from within script editor.
Can anyone help out if it is the Google issue or I am doing something stupid here.
function onOpen(e) {
//menu creation
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Formulas')
.addItem('Get Data Example', 'showExample')
.addItem('Get Fresh Data', 'queryNetPayout')
.addToUi();
};
function showExample() {
var html = HtmlService.createHtmlOutputFromFile('example')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Formulas Configuration')
.setWidth(300);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showSidebar(html);
};
//this is example.html used in sidebar
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
///////////////////////////////////////////////////////////////////////
function getFreshDataJS()
{
alert("data call rcvd");
google.script.run.queryNetPayout();
};
/////////////////////////////////////////////////////////////////////////
//SCRIPT ends here
</script>
</head>
<body>
<h3>Formula</h3>
<hr />
<form id = "configFormID" name="configForm" role="form">
<input name="getDataButton" type="button"
value="Get Data" id="getDataBtnID" onclick="getFreshDataJS()" />
</form>
</body>
</html>
//short version of function requiring urlfetch
///////////////////////////////////////////////////////////////////
function queryNetPayout(query, priceValue)
{
//for the time being, fixing the input values
query = "B00KSCABDG";
priceValue = "";
var fullData = {
output: { },
error: null,
type: "fresh query"
};
var headers = {
"Authorization" : "Basic " + scanpKey,//key credentials cannot be shared
"X-Requested-With" : "XMLHttpRequest"
};
var params = {
"method":"GET",
"headers": headers
//"muteHttpExceptions" : true
};
//this urlfetch stucks when called through google.script.run
//Or called through debug mode from script project
//works fine if called through custom formula from spreadsheet
//or called through menu item from custom menu
var res = UrlFetchApp.fetch("https://unity.scanpower.com/net-payout?upc=" + query + "&price=" + priceValue + "&marketplace=US&detail=", params);
var status = res.getResponseCode();
if(status != 200)
{
fullData.error = "Response Code: " + status;
return fullData;
}
var body = res.getContentText();
fullData.output = JSON.parse(body);
return fullData;//error = null => successful
};

How to load google chart after getting response from jquery .post() function?

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.

How can I use the data retrieved from Google Analytics and show it in Google Charts

I have performed all the query functionality where the account gets authenticated first and then get the queried result from Google Analytics.
I output the result in a table code is below;
//To Get the Profile ID first
function queryCoreReportingApi(profileId) {
updatePage('Querying Core Reporting API.');
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': lastNDays(14),
'end-date': lastNDays(0),
'dimensions': 'ga:date,ga:year,ga:month,ga:week,ga:day',
'metrics': 'ga:visitors'
}).execute(handleCoreReportingResults);
}
//To Show the Result
function handleCoreReportingResults(response) {
if (!response.code) {
if (response.rows && response.rows.length) {
var output = [];
// Profile Name.
output.push('Profile Name: ', response.profileInfo.profileName, '<br>');
var table = ['<table>'];
// Put headers in table.
table.push('<tr>');
for (var i = 0, header; header = response.columnHeaders[i]; ++i) {
table.push('<th>', header.name, '</th>');
}
table.push('</tr>');
// Put cells in table.
for (var i = 0, row; row = response.rows[i]; ++i) {
table.push('<tr><td>', row.join('</td><td>'), '</td></tr>');
}
table.push('</table>');
output.push(table.join(''));
outputToPage(output.join(''));
} else {
outputToPage('No results found.');
}
} else {
updatePage('There was an error querying core reporting API: ' +
response.message);
}
}
function outputToPage(output) {
document.getElementById('output').innerHTML = output;
}
function updatePage(output) {
document.getElementById('output').innerHTML += '<br>' + output;
}
Now the problem is how can I this returned result and show it in google charts (bars charts - pie charts etc).
I tired to use googlecharts.js but not user how to integrate. Can anyone help please
Frankly, the Getting Started guide should be exactly what you need. I'll summarize here, but I might leave out some subtleties you need to do:
Include JSAPI: <script type="text/javascript" src="https://www.google.com/jsapi"></script>
Load the library: <script type="text/javascript">google.load('visualization', '1.0', {'packages':['corechart']});</script>
Add a callback: google.setOnLoadCallback(drawChart);
Draw your charts in the drawChart function.
Then, I would go, and look at the documentation on the individual charts, and fill in the details. As you are already displaying your data as a table, I'd start with Google's Table Chart, and move on from there.

Setting Search Center URL in SharePoint 2013 using Javascript CSOM

In SharePoint 2013, I am trying to access Search object through JavaScript CSOM.
I want to know the object which can give me the access to Search Settings under Site Settings.
I tried looking under SP object but I didn't find any Search related object there.
My goal is to change the search Center URL through JavaScript CSOM.
Thanks in Advance!!!
How to set Search Settings in SharePoint 2013 via CSOM
function updateSearchSettings(searchSenterUrl,resultsPageUrl,Success,Error) {
var context = SP.ClientContext.get_current();
var web = context.get_site().get_rootWeb();
var props = web.get_allProperties();
props.set_item("SRCH_ENH_FTR_URL_SITE",searchSenterUrl);
props.set_item("SRCH_SB_SET_SITE",JSON.stringify({"Inherit":false,"ResultsPageAddress":resultsPageUrl,"ShowNavigation":false}));
web.update();
context.load(props);
context.executeQueryAsync(
function () {
var searchCenterUrl = props.get_item("SRCH_ENH_FTR_URL_SITE");
var searchPageProps = JSON.parse(props.get_item("SRCH_SB_SET_SITE"));
Success(searchCenterUrl,searchPageProps);
},
Error
);
}
//Usage
updateSearchSettings("/sites/search/pages2","/sites/search/pages/default.aspx",function(searchCenterUrl,searchPageProps){
console.log('Search Center Url:' + searchCenterUrl);
console.log('Results Page Url:' + searchPageProps.ResultsPageAddress);
},
function (sender, args) {
console.log("Error: " + args.get_message());
});
The search centre URL for a given web is stored in the Property bag for that web, on the RootWeb you can also set the search centre URL for the site.
In 2013 the keys have changed from 2010, they are now SRCH_ENH_FTR_URL_WEB and SRCH_ENH_FTR_URL_SITE respectivly.
The code to set them is something like this:
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var props = web.get_allProperties();
props.set_item("SRCH_ENH_FTR_URL_SITE","/sites/search/pages");
web.update();
ctx.load(web);
ctx.executeQueryAsync(function () {
alert("Search Settings Modified");
},
function() {
alert("failed");
});

Categories

Resources