How can I get parameters in Google Apps Script? - google-apps-script

I tried both GET and POST like the below, but Logger.log() prints only undefined.
function doGet(e){
Logger.log(JSON.stringify(e))
Logger.log(e)
var ss = SpreadsheetApp.openByUrl("MY_URL");
var sheet = ss.getSheetByName("list");
return getList(sheet);
}
function doPost(e){
Logger.log(JSON.stringify(e))
Logger.log(e)
var ss = SpreadsheetApp.openByUrl("MY_URL");
var sheet = ss.getSheetByName("list");
return getList(sheet);
}
And also tried this:
function doGet(e){
Logger.log(JSON.stringify(e.parameter))
Logger.log(e.parameter)
var ss = SpreadsheetApp.openByUrl("MY_URL");
var sheet = ss.getSheetByName("list");
return getList(sheet);
}
function doPost(e){
Logger.log(JSON.stringify(e.parameter))
Logger.log(e.parameter)
var ss = SpreadsheetApp.openByUrl("MY_URL");
var sheet = ss.getSheetByName("list");
return getList(sheet);
}
This one says it can't read parameter property because e is undefined.
I am calling APIs from Postman like this:
https://script.google.com/macros/s/MY_KEY/exec
and tried sending params with body(for POST) and Params(for GET).
And the apps script doesn't get any e.
How can I solve this problem?

Related

Replace function with text in specific cell - Apps script

I tried to use the following code to replace the current cell formula with test text instead.
function replace_content() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
cellRange.setValue("test")
return true
)
But something goes wrong and I get this error msg
Error
Exception: You do not have permission to call setValue (line 59).
Please advice.
This function runs for me with no problems:
function replace_content() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
cellRange.setValue("test")
return true;
}

Execute app script with 2 tags which will determine filter to apply and spreadsheet sheet

I'm on a project in which I get stuck just on the final step.
let me explain:
my project to filter data and move the filtered data to another spreadsheet. All work properly without issues but something happened and the issue is that I need to input dynamic data as filter and sheet name. I created 2 variables location which will determine the filter and sectionSelect which will determine the sheet name.
my goal is to send the data through the web with its tag to be filtered in the desired sheet.
FYI: the app script is bound to a gsheet.
Here is the code:
function doGet(e) {
var ss = SpreadsheetApp.openByUrl("sheetURL")
var sheet = ss.getSheetByName(Location);
return TagData(e,sheet);
}
function doPost(e) {
var ss = SpreadsheetApp.openByUrl("sheetURL")
var sheet = ss.getSheetByName(Location);
return TagData(e,sheet);
}
function TagData(e) {
var Location = e.parameter.Location; // send from app with respective tag
var sectiontSelect = e.parameter.sectiontSelect; // send from app with respective tag
sheet.append([Location, sectiontSelect])
}
function FilterOnText() {
var ss = SpreadsheetApp.getActive()
var range = ss.getDataRange();
var filter = range.getFilter() || range.createFilter()
var text = SpreadsheetApp.newFilterCriteria().whenTextContains(Location); // the location will be as per the location variable in the TagData function
filter.setColumnFilterCriteria(1, text);
}
function titleAsDate() {
const currentDate = Utilities.formatDate(new Date(), "GMT+4", "dd-MM-yyyy HH:mm:ss");
return SpreadsheetApp.create("Report of the " + currentDate);
}
function copyWithValues() {
const spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
const sourceSheet = spreadSheet.getSheetByName(sectionSelect); // fromApp variable will define which sheet the data will be copied (situated in the TagData function)
const temp_sheet = spreadSheet.insertSheet('temp_sheet');
const sourceRange = sourceSheet.getFilter().getRange();
sourceRange.copyTo(
temp_sheet.getRange('A1'),
SpreadsheetApp.CopyPasteType.PASTE_NORMAL,
false);
SpreadsheetApp.flush();
const sourceValues = temp_sheet.getDataRange().getValues();
const targetSpreadsheet = titleAsDate();
const rowCount = sourceValues.length;
const columnCount = sourceValues[0].length;
const targetSheet = targetSpreadsheet.getSheetByName('Sheet1').setName("Report"); // renamed sheet
const targetRange = targetSheet.getRange(1, 1, rowCount, columnCount);
targetRange.setValues(sourceValues);
spreadSheet.deleteSheet(temp_sheet);
}
function MoveFiles(){
var files = DriveApp.getRootFolder().getFiles();
var file = files.next();
var destination = DriveApp.getFolderById("1wan7PLhl4UFEoznmsN_BVa2y4AtFaCOr");
destination.addFile(file)
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}
function clearFilter() { // clearance of filters applied in first function
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("testo");
sheet.getFilter().remove();
}
Explanation:
Two issues:
TagData does not return anything (as Cooper pointed out)
TagData(e) has only one parameter e but you are passing two parameters TagData(e,sheet) when you call it from the doGet and doPost functions.
Not sure if this will solve all your issues, but it will solve the ones I mentioned above.
Solution:
Remove the return statements from doGet and doPost because of issue 1).
Add the sheet parameter in the TagData function.
Resulting code:
function doGet(e) {
var ss = SpreadsheetApp.openByUrl("sheetURL")
var sheet = ss.getSheetByName(Location);
TagData(e,sheet); // modified
}
function doPost(e) {
var ss = SpreadsheetApp.openByUrl("sheetURL")
var sheet = ss.getSheetByName(Location);
TagData(e,sheet); // modified
}
// added the sheet parameter
function TagData(e,sheet) {
var Location = e.parameter.Location; // send from app with respective tag
var sectiontSelect = e.parameter.sectiontSelect; // send from app with respective tag
sheet.append([Location, sectiontSelect]);
}
// rest of your code..
Or try this:
function doGet(e) {
var ss = SpreadsheetApp.openByUrl("sheetURL")
var sheet = ss.getSheetByName(Location);
var params = JSON.stringify(TagData(e,sheet)); // modified
return HtmlService.createHtmlOutput(params); // added
}
function doPost(e) {
var ss = SpreadsheetApp.openByUrl("sheetURL")
var sheet = ss.getSheetByName(Location);
ContentService.createTextOutput(JSON.stringify(e))
}
// added the sheet parameter
function TagData(e,sheet) {
var Location = e.parameter.Location; // send from app with respective tag
var sectiontSelect = e.parameter.sectiontSelect; // send from app with respective tag
sheet.append([Location, sectiontSelect]);
return { Location: Location, sectiontSelect: sectiontSelect }
}

TypeError: Cannot read property 'parameter' of undefined (line 11, file "Code") in app script

function doGet(e){
handleFunction(e);
}
function doPost(e){
handleFunction(e);
}
function handleFunction(request){
var name = request.parameter.name;
var number = request.parameter.number;
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1afoMQY/edd=0");
var sheet = ss.getSheetByName('South Clubhouse');
var rowContent = sheet.appendRow([name,number]);
}
I tried running it through postman several times I doesn't work. The params aren't working. What should I do to make it work properly?
doPost and doGet deals with payload in different ways.
function doGet(e){
var data = e.parameter;
handleFunction(data);
}
function doPost(e){
var data = e.parameter.data
handleFunction(data);
}
function handleFunction(data){
var name = data.name;
var number = data.number;
var ss =
SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1afoMQY/edd=0");
var sheet = ss.getSheetByName('South Clubhouse');
sheet.appendRow([name,number]);
}

Get Sheet ID from Sheet created by another function

I have a function that creates a form and a destination sheet for responses. I want to then reference that sheet from another function that sends out an email on form submit.
Since the create form and sheet function will be run more than once the sheet ID I need to reference will change. Trying to find ways to get it into my email function as a parameter.
function createform () {
var ss = SpreadsheetApp.create(fname);
var ssID = ss.getId();
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
ScriptApp.newTrigger('makeReport').forForm(form).onFormSubmit().create();
}
function makeReport(thispara) {
//Open Response SS
var responseSS = SpreadsheetApp.openById(thispara).getSheetByName('Sheet1');
var respRange = responseSS.getDataRange();
var respName = respRange.getValues();
}

Can not run standalone Google App Script from a Google Spreadsheet

I have a google spreadsheet shared with co-workers to keep track of task status. And I want to set a function through a menu to block some ranges in which the tasks were completed. The protective permissions are set to only allow me (owner) to edit it.
I've built a standalone script to run as me for this shared spreadsheet by using UrlFetch. I've tried many kinds of codes but it didn't work. The below are 3 versions I tried.
And, of course, I set "Who has access to the app: Anyone, even anonymous" in the standalone script.
Photo 1: Standalone script setting
Thanks so much!
1st version: Without using Content Service
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task')
var result = protection.removeEditors(protection.getEditors())
return result
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange);
Logger.log(response);
}
2nd version: Using Content Service
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task')
var result = protection.removeEditors(protection.getEditors())
return ContentService.createTextOutput(result)
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange).getContentText();
Logger.log(response);
}
3rd version: Using Content Service with JSON
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task')
var result = protection.removeEditors(protection.getEditors())
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON)
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange).getContentText();
var result = JSON.Parse(response)
Logger.log(result);
}
One problem is this line:
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
Should be:
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange().getA1Notation();
Currently, the variable taskRange is a "class" It's not a string. You need to send a string.
FINALLY IT WORKS. I think the script was not running properly because I modified many times with many kinds of code. Therefore, I've created a new one and used the "stringified" log as #SandyGood suggested.
Many thanks to you all, specially, #SandyGood.
FINAL SCRIPTS
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task');
var result = protection.removeEditors(protection.getEditors());
var resultStr = JSON.stringify(result);
Logger.log('resultStr: ' + resultStr);
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange().getA1Notation();
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange).getContentText();
Logger.log(response);
}