Google Apps Script returning a null - javascript

I have a google apps script function that is pulling data from a spreadsheet. It is able to log the information happily and then I return the data to a javascript function. But when I try to stringify and alert the information it alerts "null".
Not sure where I am going wrong!
Javascript calling the GAS function:
google.script.run.withSuccessHandler(getNews).getTheNews();
GAS function:
function getTheNews(){
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("NewsFeed");
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
Logger.log(theNews);
return theNews;
}
The GAS log:
Javascript function receiving the info:
function getNews(theNews){
var mystr = JSON.stringify(theNews);
alert(mystr);
}

Issue and workaround:
Unfortunately, it seems that in the current stage, the date object cannot be directly returned from Google Apps Script side to Javascript side. Also I could replicate your situation. I think that this is the reason of your issue. So as the current workaround, how about the following modification?
Modified script:
In this modification, the date object is converted to the string and sent to Javascript side. At Javascript side, the date string is converted to the date object.
HTML & Javascript side:
google.script.run.withSuccessHandler(getNews).getTheNews();
function getNews(theNews){
theNews = theNews.map(r => r.map(c => new Date(c))); // Added
var mystr = JSON.stringify(theNews);
alert(mystr);
}
Google Apps Script side:
function getTheNews(){
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("NewsFeed");
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
return theNews.map(r => r.map(c => c.toISOString())); // Modified
}
I think that in this case, c.getTime() instead of c.toISOString() can be also used.
Note:
For example, if you want to retrieve the display values on the cells, you can also modify as follows. In this case, Javascript is not required to be modified.
From
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
To
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getDisplayValues();
Also I found this issue at the Google issue tracker. Ref But when I saw the status, it seems "Won't Fix (Intended behavior)".
References:
toISOString()
getDisplayValues()

Related

Google script for Alphavantage gives weird results

I am trying to make a google script which i want to use in Google sheets.
I followed a tutorial video on youtube and i had the idea that my script was working well.
But then two strange things happen, and i can't figure out why.
Below is my code, this code is exactly doing what i want.
It is showing the EPS of IBM in the google sheets and also in the log.
However the moment i change the APIkey from "demo" to my own APIkey it is not working anymore.
At that moment it is still showing the EPS in the LOG, but i will get an empty cell in Google Sheets.
I have no idea why that happens.
/**
* Imports api data from alphavantage
* #customfunction
*/
function apiav(a) {
var res = UrlFetchApp.fetch(
'https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=demo'
);
var content = res.getContentText();
var json = JSON.parse(content);
var overviewvalue = json['EPS'];
Logger.log(overviewvalue);
return overviewvalue;
}
Try adding {validateHttpsCertificates: false} to your UrlFetchApp.fetch() to ignores any invalid certificates for HTTPS requests.
Your code should look like this:
function apiav(a) {
var res = UrlFetchApp.fetch('https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=ABCDEFGH', {validateHttpsCertificates: false});
var content = res.getContentText();
var json = JSON.parse(content);
var overviewvalue = json['EPS'];
Logger.log(overviewvalue);
return overviewvalue;
}
Output:
Reference:
UrlFetchApp

How to use node js (Buffer) in google apps script

I want to execute this node js line in google apps script.
How do I use this line in google apps script:
const payload = new Buffer(JSON.stringify(obj)).toString('base64');
When I run it I got this error:
ReferenceError: Buffer is not defined
I believe your goal as follows.
You want to convert const payload = new Buffer(JSON.stringify(obj)).toString('base64'); in Node.js to Google Apps Script.
Unfortunately, in the current stage, new Buffer() and Buffer.from() cannot be used with Google Apps Script. So in this case, I think that Utilities.base64Encode can be used for your situation. The sample script is as follows.
Sample script:
const obj = {key: "value"};
const payload = Utilities.base64Encode(JSON.stringify(obj));
console.log(payload) // eyJrZXkiOiJ2YWx1ZSJ9
Result:
When above script is run, eyJrZXkiOiJ2YWx1ZSJ9 is retrieved. In this case, I could confirm that the result value is the same with the following Node.js script.
const obj = {key: "value"};
const payload = new Buffer(JSON.stringify(obj)).toString('base64');
// or const payload = Buffer.from(JSON.stringify(obj)).toString('base64');
console.log(payload) // eyJrZXkiOiJ2YWx1ZSJ9
Reference:
base64Encode(data)
Buffer is used in nodeJS
The equivilant in client side JavaScript is array buffer
In order to make one from a string, you have to make a uint8array or Uint16Array from a new array buffer object with the length of the string, then loop through the array and add the char code values from the string at the index, and return the buffer
A function
function Buffer(str) {
var buf= new ArrayBuffer(str.length/*multiply by 2 for higher chars*/)
var ar = new Uint8Array(buf) //use Uint16Array etc for larger, i=0
for(i=0;i< ar.length;i++) ar[i] = str.charCodeAt(I)
return buf
}

cannot get value from google sheet through app script

I'm starting to learn how to code with Google App script and just completed the codelab playlist on Extending Google Sheets.
So to try it out I wrote a code with the intention of pulling a value from a specific cell from a sheet through a variable calles "OrderNum", using Logger to log the variable that would contain this value to check my code, but for some reason I keep getting an "(variable) is not defined)" error and I've tried multiple things already and nothing works... what I am doing wrong?? Here is my code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Create a custom menu
ui.createMenu('Order Functions')
.addItem('Copy form to database',"copy2db")
.addToUi();
}
// Pull orderNum value from sheet
function checkOrderNum() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var orderNum = sheet.getRange('H2').getValue();
}
Logger.log('var ', orderNum);
snippet of google sheet showing value of cell H2
The error I'm getting is "ReferenceError: orderNum is not define). I don't get it, it seems to me that all the references are there. Also when I remove the logger command, no error appears but then I have no idea if my code is correct, which apparently isn't.
Thanks for the help,
Nestor
You are getting an error message : "ReferenceError: orderNum is not define).
This is because your Logger statement is not part of a function.
Logger is a feature of Google scripts and Logger.log is well documented.
In the following example, I have included three versions of a Logger statement.
Logger.log("the order number is "+orderNum);: in this case the description text is in quotes, followed by the "+" operator and the variable name.
Logger.log('var %s', orderNum);: the suggestion made by #Tanaike. In the case, '%s' acts as a placeholder doc ref.
Logger.log('var ', orderNum);: this is your logger statement, but this time it is included within the function.
These statements return these results:
the order number is 1001
var 1001.0
var 1001.0
// Pull orderNum value from sheet
function checkOrderNum() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var orderNum = sheet.getRange('H2').getValue();
Logger.log("the order number is "+orderNum);
Logger.log('var %s', orderNum);
Logger.log('var ', orderNum);
}

ReferenceError: "sheet" is not defined

It is my first time to develop the google script for my google sheet
Here is the code of my script
function doGet(e) {
var url = 'https://docs.google.com/spreadsheets/d/1p3fW0Vkx89tdiws3Z-a5_LpLwyGYj7pacIek3f9Z96w/edit#gid=1862590156'
var name = '無標題表單 (回應)'
var SpreadSheet = SpreadsheetApp.openByUrl(url);
var values = sheet.getSheetValues(1, 1, 1, 1);
Logger.log(values);
}
When I run the script,and then it show the message "ReferenceError: "sheet" is not defined. (第 7 行,檔案名稱:巨集)"
I try to use the method in this article ReferenceError: "Sheets" is not defined but still cannot work.
Thank you!
tl;dr
Change var SpreadSheet to var sheet in the provided code.
As the error message is explaining: The variable sheet is not defined in the provided code.
This means at the point where sheet is trying to be used, it does not exist yet. It will have to be defined first.
Try running one of the following before you use the variable sheet
var sheet = SpreadSheet.getSheetByName('YourSheetName');
or using .openByUrl
var sheet = SpreadsheetApp.openByUrl(url);

Accessing spreadsheet in Google Script

I am writing a google script on top of a spreadsheet.
I want to deploy it as a web app.
It shows some values.
Unfortunately, with my current code, google reminds me:
TypeError: Cannot call method "getSheetByName" of null.
I have no idea where the mistake is.
Here's the code
function doGet(e) {
var app = UiApp.createApplication().setTitle('Details');
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var dataFromCell = ss.getRange("B4").getValue();
var mypanel = app.createVerticalPanel();
var label = app.createLabel(dataFromCell);
app.add(mypanel);
app.add(label);
return app;
}
In standalone webapps you cannot use getActiveSpreadsheet because no one is using it actively...
Use SpreadsheetApp.openById('ID') instead, you can get the ID in the url of your spreadsheet like in this example :
https://docs.google.com/spreadsheet/ccc?key=0AnqSFd3iikE3d-------nZIV0JQQ0c1a3dWX1dQbGc#gid=0
between key= and #, ie 0AnqSFd3iikE3d-------nZIV0JQQ0c1a3dWX1dQbGc
Not need to use ID , just try this code ( change mygooglelocation with your Spreadsheet name and range of cells. Working very well for me with google maps...
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('mygooglelocation');
var ss = SpreadsheetApp.getActive();
var mylocationInfo = ss.getRange("A2:B4").getValues();

Categories

Resources