I've mashed together a couple of functions for Google Apps Script but I'm getting a syntax error at the end. I'm a beginner and I'm not sure why Google Sheets Script editor is giving me the syntax error on the very last line.
function CheckSales() {
// Fetch the monthly sales
var monthSalesRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Day Breakdown").getRange("K35");
var monthSales = monthSalesRange.getValue();
// Check totals sales
if (monthSales > 999){
function sendEmail() {
var recipient = "myemail";
var subject = "SubjectTest";
var body = "Simple Message + monthSales variable tag here.";
MailApp.sendEmail(recipient, subject, body);
}
}
Syntax error: SyntaxError: Unexpected end of input line: 13 file: unit_notifier.gs
I'm a beginnier so I didn't know what to do or where to turn.
I tried deleting the trailing "}".
Removing part of the script.
I would appreciate learning what I did wrong and any tips on resources for the future. I'm am incredibly grateful. Thank you.
try it this way:
function checkSales() {
var monthSalesRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Day Breakdown").getRange("K35");
var monthSales = monthSalesRange.getValue();
if (monthSales > 999) {
var recipient = "myemail";
var subject = "SubjectTest";
var body = "Simple Message " + monthSales;
MailApp.sendEmail(recipient, subject, body);
}
}
If you wish to create a standalone sendEmail function then you can but you need to have some parameters to pass recipient, subject and body and the call would simply be something like sendEmail(recipient,subject,body);
It appears to be that the sendEmail function is defined but you never called it and the variable monthSales is not included in the body of the email. Try this possible approach.
function checkSales(){
// Fetch the monthly sales
var monthSalesRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Day Breakdown").getRange("K35");
var monthSales = monthSalesRange.getValue();
// Check totals sales
if (monthSales > 999){
sendEmail(monthSales);
}
}
function sendEmail(monthSales) {
var recipient = "myemail";
var subject = "SubjectTest";
var body = "Simple Message. Total sales for the month: " + monthSales;
MailApp.sendEmail(recipient, subject, body);
}
Related
Exception: Cannot call SpreadsheetApp.getUi() from this context. at CheckInventory(onChange2:13:27)
I am getting the above error when my code runs. I have it set to an onchange trigger. It checks the values in one column of my spreadsheet and compares it to another. I don't believe the issue lies in that, but rather somewhere else? my code is as follows;
// Check inventory and send email on Change to Column AA (27)
function CheckInventory() {
// Fetch the current inventory)
var currentRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master").getActiveRange().getA1Notation();
var currentRow = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master").getActiveRange().getRow();
var currentColumn = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master").getActiveRange().getColumn();
var currentInventoryRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master").getRange(currentRow,11);
var currentInventory = currentInventoryRange.getValue();
var oneMonthInventoryRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master").getRange(currentRow,27);
var oneMonthInventory = oneMonthInventoryRange.getValue();
var currentSKU = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master").getRange(currentRow,1).getValue();
var ui = SpreadsheetApp.getUi();
// Check totals sales
if (currentColumn === 27){
if (currentInventory < oneMonthInventory){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange("B2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'Item SKU ' + currentSKU + ' inventory is low! Reorder now.'; // Second column
var subject = 'Low Inventory Notification: ' + currentSKU;
MailApp.sendEmail(emailAddress, subject, message);
}}
}
Any thoughts on why this is breaking and not triggering properly?
I have tried updating the ui line and checked it to ensure it was written properly, but it did not fix it.
I had a syntax error with a simple code line of google sheet app scripts, I am not experienced in app scripts but this is pretty straight forward syntax from any programming language. Kindly show me if I'm missing something?
I tried changing header into 'header' or "header" but syntax error was on it not recognizing the format
function loadInformation(){
//Set up service and check access
var firebaseService = getFirebaseService();
if (firebaseService.hasAccess()) {
//Set up google sheet and header row
var ss = SpreadsheetApp.getActiveSpreadsheet();
var Sheet = ss.getSheetByName("<YOUR SHEETNAME>");
Sheet.clearContents();
Sheet.appendRow([<YOUR SHEET HEADERS>]);
//Set up reference
var databaseURL = "https://xxxxxx.firebaseio.com/";
var ref = "xxxxxx";
var requestURL = databaseURL+ref+".json";
//API Call
var response = UrlFetchApp.fetch(requestURL, {
headers: {
Authorization: 'Bearer ' + firebaseService.getAccessToken()
},
method: 'get'
});
//Parse JSON
var data = JSON.parse(response.getContentText());
//Loop through JSON and append row
for (item in data){
var newRow = [item,];
Sheet.appendRow(newRow);
}
}
} else {
//Show authorization URL to user
var authorizationUrl = firebaseService.getAuthorizationUrl();
showDialog(authorizationUrl);
}
}
Error Result :
Syntax error. (line 20, file "loadInformation") Dismiss
Your "else" is outside the function. Delete the " } " before the "else".
Also, if this line is left like this it will throw another error. Be sure to have the headers actually there:
Sheet.appendRow([<YOUR SHEET HEADERS>]);
like this:
Sheet.appendRow(["a", "b", "c"]);
Like Mark said, your 'else' is outside the function.
And if you change this
Sheet.appendRow([<YOUR SHEET HEADERS>]);
to
Sheet.appendRow(["<YOUR SHEET HEADERS>"]);
the syntax error should go away.
I'm writing a script that takes google sheet data and uploads my mailchimp subscriber data, where the edited cell values are sent over as updated merge tags. The original code came from here. I've got the script running successfully, accept for this one error:
"Invalid Resource","status":400,"detail":"Blank email address"
I understand the error according to the documentation in the mailchimp api documentation, but I'm not sure why it's not recognizing the subscriber data from the script:
var emHash = md5(em.toLowerCase()); //this is pulled from my md5 function
var payload = JSON.stringify({
"status_if_new": "subscribed",
"email_address": em,
"merge_fields": {
"LEAD": lead,
//rest of vars following same syntax
}
});
var options = {
"headers" : headers,
"payload": payload,
"method" : "put",
"muteHttpExceptions" : true
};
var response = UrlFetchApp.fetch('https://us15.api.mailchimp.com/3.0' + '/lists/' + 'xxxxxxx' + '/members/' + emHash,options);
Logger.log(response);
}
Last is the function triggered by editing so that changed values get sent over via the function above
function onEdit(e) {
var activeSheet = e.source.getActiveSheet();
var range = e.range;
var rowedited = range.getRowIndex();
if (activeSheet.getName() !== "ATTENDANCE"){
return;
Logger.log("Oops :(");
}
else {
var values = sheet.getRange(rowedited, 1, 1, 13).getValues()[0];
var em = values[2];
var lead = values[1];
//remaining vars omitted for brevity
sendToMailChimp_(em,lead...[etc.]);
}
Any thoughts?
I figured it out - I pulled an amateur move and had the columns attributed to the wrong array element.... So yes, I started at 1 and not 0
facepalm
It is now working!
I'm using Google Apps Script to write values from a form to a Google Spreadsheet.
I have the form in my HTML page and its action calls the Google Apps Script to write in the sheet.
Now I'd like to go back to my site with a flag var and show a message (Error or Complete) based on the result of the function.
I know how to create and set the flag variable but I don't know how to "send" it to my page. I was only able to show my flag with something like this (that's the whole function I have in GAS)
function doPost(e){
var id = "";
var name = e.parameter['name'];
var surname = e.parameter['surname'];
var serial = e.parameter['serial'];
var eMail = e.parameter['email'];
var text = e.parameter['text'];
var date = new Date();
var ans = ""
var ctrl= "WIP";
var vals = [id, date, name, surname, serial, eMail, text, ans, flag];
var sheetObj =SpreadsheetApp.openById("myKey").getSheetByName('Requests').appendRow(vals);
return ContentService.createTextOutput(someOutput);
}
Someone knows how to do what I need?
Thanks a lot for your help!
S.
You can do something like this
return ContentService.createTextOutput("Complete").setMimeType(ContentService.MimeType.TEXT);
Or in case of exception return 'Error' from your catch block like this
return ContentService.createTextOutput("Error").setMimeType(ContentService.MimeType.TEXT);
I am fairly new to js and node.js but I have managed to get the calls going to the API and getting the necessary information. However when I was attempting to continue to raise the batter id to get the next information available. I have successfully gotten the undefined error check to work as well. But I was unable to loop through because I was trying to perform something immediately on an async function. I am now trying to make the entire function async with a 2 second delay after each run, but it is returning the following error (i'm assuming because something is undefined)
**Note: When I just get the value for i=4 and p=1 the value does exist in the API data. However it gives this error when I attempt to start with those values using this code.
error:
Unexpected token u in JSON at position 0
this is my code:
request('API Info redacted',
setTimeout (function (err, response, body) {
//do stuff below
//to get the first play of the game, set i=1 and p=0
var i = 4;
var p = 1;
// ************
var boolIn = 1;
// parse the body as JSON
var parsedBody = JSON.parse(body);
var apiResults = parsedBody.apiResults;
if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined') {
//sets the variables to the first batter of the next inning
p=0;
i = i+1;
}
//below pulls the apiResults from the body of the API request
var sportId = apiResults.sportId;
var hitName = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].name;
var fname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.firstName;
var lname = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].batter.lastName;
var outsB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.before;
var outsA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].outs.after;
var rbis = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].runsBattedIn;
var outDifference = (outsA - outsB);
var hitB = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.beforeId;
var hitA = apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p].baseSituation.afterId;
var baseDifference = (hitA - hitB);
//prints the details pulled above
res.json("First Name: " + fname + ", Last Name: " + lname + ", Hit name: " + hitName + ", Outs on the play: " + outDifference + ", Rbi's: " + rbis +
", Base Sit: " + baseDifference);
//increases the batter call
p = p+1;
//below ends the setTimeout
}, 2000));
//ended request
});
setTimeout will not pass arguments to the function it calls, so body is undefined. When you pass that to JSON.parse, it will be converted to the string "undefined", which isn't a valid JSON text.
Nowhere is your code do you show any JSON coming into your program (or embedded into it). You need to have some JSON to parse before you try to parse it.