update spreadsheet in serverside code run from client html javascript not working - javascript

I have an html where user requests add and enters data. The javascript in the body of the html calls the server side. I am unable to connect with the sheet either with saved ID or URL in order to add the row.
I cannot update of my spreadsheet despite #Serge insas comment that openById "it means "open for read and write". Am I making a simple mistake or is this impossible. The code initiated from the client side is running in the server.
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById("[ssId]").getSheetByName('Sheet1');
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById("ssId").getSheetByName('Sheet1');
Both get Error: Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.
const ssUrl = PropertiesService.getScriptProperties().getProperty('ssUrl');
var sheet = SpreadsheetApp.openByUrl("ssUrl").getSheetByName('Sheet1');
Gets error: Exception: Invalid argument: url
ABOVE IS THE IMPORTANT PART
/**
* this code is run from the javascript in the html dialog
*/
function addMbrCode(myAddForm) {
// removed logging
console.log("Beginning addMbrCode" );
paragraph = body.appendParagraph('Beginning addMbrCode.');
// Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.
// const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
// var sheet = SpreadsheetApp.openById("[ssId]").getSheetByName('Sheet1');
// var sheet = SpreadsheetApp.openById("ssId").getSheetByName('Sheet1');
// Exception: Invalid argument: url
const ssUrl = PropertiesService.getScriptProperties().getProperty('ssUrl');
var sheet = SpreadsheetApp.openByUrl("ssUrl").getSheetByName('Sheet1');
myAddForm = [ fName, lName, inEmail, fallNum, winNum, sprNum];
var fName = myAddForm[0];
var lName = myAddForm[1];
var inEmail = myAddForm[2];
var fallNum = myAddForm[3];
var winNum = myAddForm[4];
var sprNum = myAddForm[5];
var retCd = '';
/**
* 10 - successful add
* 20 - duplicate - not added
*/
var combNameRng = sheet.getRange(2, 4, numRows).getValues();
var inCName = (fName + '.' + lName).toString().toLowerCase();
if (combNameRng.indexOf(inCName) > 0 ) {
console.log("Alert: Not adding duplicate "
+ fName + ' ' + lName + " retCd: " + 20 );
paragraph = body.appendParagraph("Not adding duplicate "
+ fName + ' ' + lName + " retCd: " + 20);
retCd = 20;
return retCd;
}
sheet.appendRow([fName.toString().toLowerCase()
, lName.toString().toLowerCase()
,
, inEmail.toString().toLowerCase()
]);
const currRow = sheet.getLastRow().toString();
);
retCd = 10;
return retCd;
}
If this makes a difference, here is the javascript from the body of my html in the dialog window.
<script>
document.querySelector("#myAddForm").addEventListener("submit",
function(e)
{
alert('begin addEventListener');
e.preventDefault(); //stop form from submitting
var retCd = google.script.run.addMbrCode(this); // client side validation
document.getElementById('errMsg').textContent = 'Successful member
return false; // do not submit - redisplay html
}
);
</script>
Removed unneeded coding detail
Per #iansedano I created an object/array to use instead of this and added the successhandler and failurehandler. In either case I want to see the html again with my message. This is the current script. Response is so doggy I am not seeing alerts, Logger.log, or console.log. Crazy shoppers using my internet!
<script>
document.querySelector("#myRmvForm").addEventListener("submit",
function(e)
// removed alerts and logging
// removed client side validation for simplicity
cSideValidate();
// Then we prevent the form from being submitted by canceling the event
event.preventDefault();
});
function cSideValidate() {
dataObj = [
document.getElementById('fName').value,
document.getElementById('lName').value,
document.getElementById('email').value
];
var retCd = google.script.run.withSuccessHandler(serverReply)
.withFailureHandler(serverReply)
.rmvMbrCode(dataObj); // server side validation
}
function serverReply {
// logic to set the correct message - this is an example
document.getElementById('errMsg').textContent
= 'Successful delete using email.';
}
</script>
Nothing is being added to my spreadsheet so the server side code is not working. I see my loggin so I know it is getting there.

You're getting ssId from the script properties and assigning it to the ssId variable, but then you pass a string ("ssId") to the openById() function, not the value of the variable.
Try the following please:
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById(ssId).getSheetByName('Sheet1');

Related

How to append event listener script to dynamically created element formed from server side event data

I've looked through various similar questions but honestly I don't understand any of the answers (such as they are) in order to apply any of them to what I've written. I'd really appreciate some help as I'm extremely new to this and I'm very lost!
I'm attempting to update an existing page used by moderators for clearing created data as it comes in from users. It uses server side events to check for new items, the old version uses regular forms but the page takes too long to refresh after submitting data. I'm trying to use to set the form data in the background without the need for a refresh but I'm struggling to get the event listeners to attach to the visual elements. They are created dynamically from the event source data. Visually the output looks how I want it to, but it's not behaving as it needs to. One response to a similar-ish question said don't trust the console log, it could be working, but it definitely isn't, the process on the receiving end is a copy of the existing form handler for the old page, so I know that works.
I'm unsure if it's a syntax error or if I need a different approach, the errors I'm getting look like this - it can't find the element I want it to attach the script to:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at :1:37
at EventSource.source.onmessage (MOD.php:39)
This is what I've written on the receiving page:
window.onload = function() {
var last = "";
var lastqueue = "";
var source = new EventSource("MOD-data.php");
source.onmessage = function(event) {
var mydata = event.data;
var data = mydata.split('&&');
var upddate = (data[0]);
var queuedata = (data[1]);
if (mydata != last) {
last = mydata;
if (queuedata != lastqueue) {
var Qdata = queuedata.split('||');
for (let i = 0; i < Qdata.length; i++) {
var itmdata = Qdata[i].split('.');
var itmID = "Q" +(itmdata[0]);
var exists = document.getElementById(itmID);
if (exists === null) {
var itmclass = (itmdata[1]);
var itmbg = (itmdata[2]);
var itmwho = (itmdata[3]);
var itmimg = (itmdata[4]);
var rewbox = "<div id=\"" + itmID + "\" class=\"Qitm " + itmclass + "\" style=\"background:#" + itmbg + "\">" + itmwho + "<input type=\"image\" class=\"rew\" name=\"submit\" src=\"/web/rewards/" + itmimg + ".png\"></div>";
document.getElementById("Qcon").innerHTML += "" + rewbox + "";
var newScript = document.createElement("script");
var inlineScript = document.createTextNode("document.getElementById(" + itmID + ").addEventListener(\"click\", Qclear, true);function Qclear() {\$.ajax({type: \"POST\",url: \"MOD-queue-clear.php\", data: \"timestamp=" + itmID + "\"})}");
newScript.append(inlineScript);
document.getElementById(itmID).appendChild(newScript);
};
};
lastqueue = queuedata;
};
document.getElementById("debug").innerHTML = "<!--" + queuedata + "-->";
};
};
};

getChild of body of gmail email using Goole Apps Scripts (GAS)

Problem
I have automated emails coming to me with particular client details in them. I have the repetitive task of repling to each email with a template. I am wanting to automate the process utilising Google Apps Scripts.
Where I'm up to
I have worked out how to collect the body of the email I am replying to. I'm trying to get the third paragraph info and store this in a variable.
Here is my code:
function autoReply() {
//Capturing the automated email
var queryInbox = "is:unread from:(example#gmail.com)";
var locatedEmail = GmailApp.search(queryInbox);
for (var i in locatedEmail){
var thread = locatedEmail[i];
var messages = thread.getMessages();
var msgBody = messages[i].getBody();
var clientsEmail = msgBody.getChild('p')[3]; //Attempting to obtain the third paragraph of the body.
if(messages.length === 1) {
var body = "<p> The clients email is: " + clientsEmail + "</p>";
};
var options = { name: "Temp Name",htmlBody: body };
thread.reply(body, options);
thread.markRead();
thread.moveToArchive();
}
};
Note: Img attached for context.
I believe your goal as follows.
When the thread has one message, you want to retrieve the body of email.
You want to retrieve the 3rd paragraph from the message of email.
You want to reply the message including the retrieved 3rd paragraph.
Modification points:
At for (var i in unread){, I thought that you might use locatedEmail.
When you want to reply the message with messages.length === 1, var msgBody = messages[i].getBody(); is required to be modified. Because in your for loop, the index i is used for var thread = locatedEmail[i]; and var msgBody = messages[i].getBody();.
In your case, I think that getPlainBody() instead of getBody() might be suitable.
When above points are reflected to your script, it becomes as follows.
Modified script:
function autoReply() {
var queryInbox = "is:unread from:(example#gmail.com)";
var locatedEmail = GmailApp.search(queryInbox);
locatedEmail.forEach(thread => {
var messages = thread.getMessages();
if (messages.length === 1) {
var msgBody = messages[0].getPlainBody();
var clientsEmail = msgBody.split("\n")[2]; // Here, the 3rd paragraph is retrieved.
var body = "<p> The clients email is: " + clientsEmail + "</p>";
var options = { name: "Temp Name",htmlBody: body };
thread.reply(body, options);
thread.markRead();
thread.moveToArchive();
}
});
}
Reference:
getPlainBody()

JavaScript: Catch errors in async function and stop the rest of the function if there are any

EDIT: ANSWER BELOW
I'm making my first JavaScript project and decided to make a simple weather app. It fetches weather data of a city you put in from the openweathermap.org api and displays it in a table. I firstly made it using fetch() and .then. I then learned about async functions and the await keyword. After converting the script to an asynchronous function, I came across a problem. If the first city you enter isn't a real city (an error is catched while fetching the api), the warning message appears, BUT the table also appears because the rest of the function still executes.
So my question is: how can I stop the async function if any errors are catched?
Here's the website: https://lorenzo3117.github.io/weather-app/
Here's the code:
// Launch weather() function and catch any errors with the api request and display the warning message if there are any errors
function main() {
weather().catch(error => {
document.querySelector("#warningMessage").style.display = "block";
console.log(error);
});
}
// Main function
async function weather() {
// Take city from input and reset input field
var city = document.querySelector("#cityInput").value;
document.querySelector("#cityInput").value = "";
// Get api response and make it into a Json
const apiResponse = await fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=<apiKey>&units=metric");
const jsonData = await apiResponse.json();
// Removes warning message
document.querySelector("#warningMessage").style.display = "none";
// Puts the Json into an array and launches createTable function
var arrayJson = [jsonData];
createTable(document.querySelector("#table"), arrayJson);
// Function to create the table
function createTable(table, data) {
// Makes the table visible
document.querySelector("#table").style.display = "block";
// Goes through the array and makes the rows for the table
for (let i = 0; i < data.length; i++) {
let rowData = data[i];
var row = table.insertRow(table.rows.length);
// This var exists to make the first letter capitalized without making a gigantic line (see insertCell(3), line 53)
// Could be made into a function if needed
var weatherDescription = rowData.weather[0].description;
// Take latitude and longitude for google maps link
var lat = rowData.coord.lat;
var long = rowData.coord.lon;
// Make an a-tag for link to google maps
var mapLink = document.createElement("a");
mapLink.innerHTML = "Link";
mapLink.target = "_blank";
mapLink.href = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + long;
// Making rows in table
row.insertCell(0).innerHTML = rowData.name + ", " + rowData.sys.country;
row.insertCell(1).innerHTML = rowData.main.temp + " °C";
row.insertCell(2).innerHTML = rowData.main.humidity + "%";
row.insertCell(3).innerHTML = weatherDescription.charAt(0).toUpperCase() + weatherDescription.slice(1);
row.insertCell(4).appendChild(mapLink); // appendChild for anchor tag because innerHTML only works with text
}
}
And the repo: https://github.com/lorenzo3117/weather-app
Thank you
you can do this :
async function weather() {
try {
const apiResponse = await fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=02587cc48685af80ea225c1601e4f792&units=metric");
} catch(err) {
alert(err); // TypeError: failed to fetch
return;
}
}
weather();
Actually, the error catched isn't an error with the api itself because the api still sends a json, but the error is catched while trying to read a certain object from the json (which doesn't exist because the json isn't a normal one with weather data). Therefore the function stops far later than expected, after the table was made visible.
I just put the line that made the table visible after the function that creates the table (after where the real error occurs). Also thanks #Dadboz for the try catch method which made the code even more compact. I also added an if else to check if the json file is the correct one so unnecessary code doesn't get executed. Thanks #James for pointing this out to me.
Here's the final code:
// Main function
async function weather() {
try {
// Take city from input and reset input field
var city = document.querySelector("#cityInput").value;
document.querySelector("#cityInput").value = "";
// Get api response and make it into a Json
const apiResponse = await fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=<apiKey>&units=metric");
const jsonData = await apiResponse.json();
if (jsonData.message == "city not found") {
document.querySelector("#warningMessage").style.display = "block";
} else {
// Removes warning message
document.querySelector("#warningMessage").style.display = "none";
// Puts the Json into an array and launches updateTable function
var arrayJson = [jsonData];
updateTable(document.querySelector("#table"), arrayJson);
}
}
catch (error) {
console.log(error);
}
}
// Function to update the table
function updateTable(table, data) {
// Goes through the array and makes the rows for the table
for (let i = 0; i < data.length; i++) {
let rowData = data[i];
var row = table.insertRow(table.rows.length);
// This var exists to make the first letter capitalized without making a gigantic line (see insertCell(3), line 53)
// Could be made into a function if needed
var weatherDescription = rowData.weather[0].description;
// Take latitude and longitude for google maps link
var lat = rowData.coord.lat;
var long = rowData.coord.lon;
// Make an a-tag for link to google maps
var mapLink = document.createElement("a");
mapLink.innerHTML = "Link";
mapLink.target = "_blank";
mapLink.href = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + long;
// Making rows in table
row.insertCell(0).innerHTML = rowData.name + ", " + rowData.sys.country;
row.insertCell(1).innerHTML = rowData.main.temp + " °C";
row.insertCell(2).innerHTML = rowData.main.humidity + "%";
row.insertCell(3).innerHTML = weatherDescription.charAt(0).toUpperCase() + weatherDescription.slice(1);
row.insertCell(4).appendChild(mapLink); // appendChild for anchor tag because innerHTML only works with text
}
// Makes the table visible
document.querySelector("#table").style.display = "block";
}
Thanks everyone for your answers, have a good day!
Lorenzo

Trying to understand getThreads in GAS

I am new to app script and I am trying to read an email from my inbox. I thought that getThreads would do the job but I still don't fully understand how to use it. When I try to execute the code I wrote below it comes up with a null error.
Looking at the documentation of getThreads(), they use the example:
// Log the subject lines of the threads labeled with MyLabel
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
Logger.log(threads[i].getFirstMessageSubject());
}
what does "MyLabel" stand for?
This is the code i tried that failed
function myFunction() {
var label = GmailApp.getUserLabelByName('bobtheman#gmail.com');
var threads = label.getThreads();
for (var t in threads) {
var thread = threads[t];
// Gets the message body
var message = thread.getMessages()[0].getPlainBody();
}
GmailApp.sendEmail('barbrabat#gmail.com', 'hola', message)
}
MyLabel is the label of the email. It depends whether you added a label to a specific email or not. You can use the search method instead.
function myFunction(){
var label = 'yourLabel'; // if no label, remove the label in search
// it would be better if you add a label to a specific email for fast and more precise searching
var searchEmail = GmailApp.search('from:me subject:"' + subject + '" label:' + label + '');
var threadId = searchEmail[0].getId(); // get the id of the search email
var thread = GmailApp.getThreadById(threadId); // get email thread using the threadId
var emailMsg = thread.getMessages()[0]; // get the content of the email
var emailContent = emailMsg.getPlainBody(); // get the body of the email
// check using log
Logger.log(emailContent);
// how to open log
// Ctrl + Enter
// Run this function before checking the log
}
Thanks

JavaScript Class Objects not returning value

I've been working with the Microsoft Bot Framework to create a bot that can interface between MS Teams and AWS. I've been trying to write some JS functions but have been unsuccessful in getting them to operate how I want them to.
Here is what I am currently working on and am stuck on:
I am creating a 'ping' like functionality so a bot user can ping an instance in AWS and receive its status whether its running and has passed the system checks or not. My code is currently able to take the user request for the ping, retrieve the information from AWS, and can even print that info to the console. However, when I am trying to retrieve that information back out of the object that I set it to and print it to MS Teams, it says my variable is undefined.
Some code snippets are below:
class aws_Link {
constructor (mT, ping_1, i_state, i_status) {
this.myTag = mT;
this.ping = ping_1;
this.instance_state = i_state; // I declare this here, but should I?
this.instance_status = i_status; // I declare this here, but should I?
}
//i_state and i_status are just passed NULL when the object is initialized
//so they would be holding some value, not sure if I have to do this
api_link () {
var mainLink = API_LINK_TAKEN_OUT_FOR_OBVIOUS_REASONS;
var myTagFill = "myTag=";
var ampersand = "&";
var pingFill = "ping=";
var completeLink = String(mainLink + myTagFill + this.myTag + ampersand + pingFill + this.ping);
var finalLink = completeLink;
finalLink = finalLink.split(' ').join('');
//set up API-key authenticication
var options = {
url: finalLink,
headers: {
'x-api-key': 'AWS-PRIVATE-TOKEN'
}
};
if(this.ping == "TRUE") { // if the user wants to use /ping
var res = request(options, function(error, response, body) {
console.log("PING REQUEST"); //debug
body = JSON.parse(body);
var h_state = body['instanceState'];
var h_status = body['instanceStatus'];
this.instance_state = h_state;
this.instance_status = h_status;
console.log("STATE: " + h_state); //debug
console.log("STATUS: " + h_status); //debug
});
}
}
pingFunction () {
var tmp = "Instance State: " + this.instance_state + " Instance Status: " + this.instance_status;
return tmp;
}
}
And here is where I call the api_link() function and pingFunction():
var apiLink1 = new aws_Link("MY_TAG_VALUE", "TRUE", "NULL", "NULL");
var completeAPILink = apiLink1.api_link();
session.send('Request complete.');
session.send("PING: " + apiLink1.pingFunction());
So essentially the user enters in some info which gets passed to where I create the "new aws_Link" which then a my understanding is, creates an object called apiLink1. From there, it makes the request to AWS in my api_link() function, which retrieves the info I want. I thought I was then saving this info when I do the: this.instance_state = h_state; & this.instance_status = h_status;. So then when I call pingFunction() again on apiLink1, I thought I would be able to retrieve the information back out using this.instance_state and this.instance_status, but all it prints out is undefined. Any clarification on why my current code isn't working and any changes or improvements I can make would be greatly appreciated.
Thanks!

Categories