Instant Chat on Web Application Using Firebase Database JavaScript - javascript

In my website I am creating a instant messaging service using Firebase data base. I have got the functionality of the chat working so users can send a message to the chat which will display in the display box.
The problem I'm having is, when a new chat is created and users begin a conversation, the messages appear in order of the conversation they're having as they should As seen below:
but when the page is refreshed and the messages are pulled from the database is displays as follows.
My db structure for the chat is as follows:
And my JS code is for the chat is:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var db = firebase.database();
var currentProperty = localStorage.getItem("prop");
db.ref('addresses/'+currentProperty+'/chat/group').on("child_added", function(data){
//Set Local Variables
var message = data.child("message").val();
var date = data.child("date").val();
var sender = data.child("uid").val();
var time = data.child("time").val();
var who;
var getCurrentDate = new Date;
day = getCurrentDate.getDate();
month = getCurrentDate.getMonth() + 1;
year = getCurrentDate.getFullYear();
var newDate = [day, month, year].join('/');
var title = document.getElementById("chatTitle");
db.ref('addresses/'+currentProperty+'/firstLine').once("value", function(snapshot){
title.innerHTML = "<i class='fas fa-home' style='font-size:150%;margin-right:10px'></i>Group chat with all persons involved with " + capitalLetter(snapshot.val());
});
if(sender == user.uid){who = 'boxCurrent currentUser';}
else
{who = 'boxOther otherUser';}
if(date == newDate){date = 'Today'}
db.ref('users/'+sender+'/firstName').on('value', function(data){
var name = data.val();
if(who == 'boxCurrent currentUser'){
var messageD = "<div id='userMessageDisplay' style='width:100%;text-align:end;'><span class='message-data-time'>"+time+", "+date+" </span><span id='userName'>"+name+"</span><div id='hello' class='"+who+"' style= height:100%;'>"+message+"</div></div>";
$('#displayBox').append(messageD);
}
else{
var messageD = "<div id='userMessageDisplay' style='width:100%;'><span class='message-name'>"+name+"</span><span class='message-data-time'> "+time+", "+date+"</span><div id='hello' class='"+who+"' style='width:70%; height:100%;'>"+message+"</div></div>";
$('#displayBox').append(messageD);
}
});
});
db.ref('addresses/'+currentProperty+'/tenant').orderByKey().once("value", function(snapshot){
snapshot.forEach(function(child){
var key = child.key;
console.log(key);
db.ref('users/'+key+'/firstName').once("value", function(data){
var first = data.val();
var appendFirst = "<li style='padding: 5px 10px 0 10px; height:75px;'><i class='fas fa-user-circle' style='font-size:400%; float:left;color:#6a6c75;'></i><div class='about' style='height:100%;padding: 10px 0 0 70px;'><div id='append2"+key+"' class='profileName' style='color:#fff;'>"+first;
$('#peopleList').append(appendFirst);
});
db.ref('users/'+key+'/lastName').once("value", function(data){
var last = data.val();
var appendLast = " "+last+"</div>"
$('#append2'+key).append(appendLast);
});
db.ref('users/'+key+'/onlineStatus').once("value", function(data){
var onlineStatus = data.val();
console.log(onlineStatus);
if(onlineStatus == 'Online'){
var appendStatus = "<div class='status' style='color:#a8aac3;'><i class='fa fa-circle' online style='color:#86BB71; margin-right:10px;font-size:80%;border:1px solid #fff;border-radius:50%;'></i>Online</div></div></li>"
$('#append2'+key).append(appendStatus);
}
else{
appendStatus = "<div class='status' style='color:#a8aac3;'><i class='fa fa-circle offline' style='color:#E38968;margin-right:10px;font-size:80%;border:1px solid #fff;border-radius:50%;'></i>Offline</div></div></li>"
$('#append2'+key).append(appendStatus);
}
});
});
});
} else {
// No user is signed in.
location = 'index.html'
}
});
function sendMessage(){
var theDiv = document.getElementById('displayBox');
var message = document.getElementById("messageInput").value;
var currentProperty = localStorage.getItem("prop");
var user = firebase.auth().currentUser;
//date
var date = new Date;
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
var newDate = [day, month, year].join('/');
var db = firebase.database();
//time
hours = date.getHours(); // => 9
mins = date.getMinutes(); // => 30
var time = [hours, mins].join(':');
console.log(time);
var messageDetails = {
"uid": user.uid,
"message": message,
"date": newDate,
"time": time
}
if(message == ''){
document.getElementById("messageInput").style.border = '1px solid red';
}
else{
db.ref('addresses/'+currentProperty+'/chat/group').push(messageDetails).then(function(){
document.getElementById("messageInput").value = '';
theDiv.scrollTop = '99999';
});
}
}
Apologies for the long post but does anyone know why when the page is refreshed, the messages are clustered buy the user who sent the message?
Also any solutions to resolved the problem will be extremely helpful.
Thanks in advance.

I would recommend changing the way you store your message timestamps. I would store them as firebase timestamps like this: https://firebase.google.com/docs/reference/js/firebase.database.ServerValue
and then when you pull them, you want to use orderByChild and then startAt from the retrieve data information found here: https://firebase.google.com/docs/database/admin/retrieve-data
This will then order the messages based on their timestamp instead of their keys.

Related

Creating a Reminder Discord Bot (Discord.js)

I am writing my first Discord bot and I am fairly new to JavaScript, especially dealing with libraries such as Discord.JS. My project here is a Reminder Discord bot, which takes a user input by prefix, stores and checks data based on time, then outputs a user inputted message when the user time set is the same as current time (to alert).
My current issue is that I don't know how to send a message to a discord channel using the client outside of the two specificed scopes. Ideally, I'd like to send a message between
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
Thank you
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permissions } = require(`discord.js`);
const { type } = require("os");
const prefix = '!';
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
var machineTime = null;
var userTime = null;
// Discord Client Ready Check
client.on("ready", () => {
console.log("Bot is online!")
})
// Message Listener
client.on("messageCreate", (message) => {
if (message.author.bot) return;
//Split input into array & get current date
var content = message.content.split(" ");
console.log(content);
// Output
if (content[0] === prefix + 'set-reminder'){
//Start timer
setInterval(checkTime, 1000);
//Convert user time
var inputTime = content[2].split(':');
var inputDate = content[1].split('/');
//Change store metrics and format date
var convertMinutes = parseInt(inputTime[1]);
var convertHours = parseInt(inputTime[0]);
var convertMonth = parseInt(inputDate[0]);
var convertDay = parseInt(inputDate[1]);
var formatDate = convertMonth + "/" + convertDay + "/" + inputDate[2];
//If PM add 12 hours to time input
if (content[3].toLowerCase() === "pm") {
convertHours += 12;
}
userTime = formatDate + " " + convertHours + " " + convertMinutes;
//Send reminder confirmation
message.channel.send("Members will be alerted at " + content[1] + ":white_check_mark:");
}
// Input Array: 0 = prefix, 1 = date, 2 = time, 3 = am/pm, 4 = channel, 5 = message
})
//Current Time Check
const checkTime = () => {
var machineOutput = new Date();
var machineDate = machineOutput.toLocaleDateString();
var machineMinutes = machineOutput.getMinutes();
var machineHours = machineOutput.getHours();
machineTime = machineDate + " " + machineHours + " " + machineMinutes;
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
console.log(machineTime);
}
client.login("MY_LOGIN_KEY");```
As long as you have access to the client, you can send a message to any channel.
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
const channel = await client.channels.fetch('channel id');
channel.send('...');
}

Multi-user login webpage with time recorder using JS

I have been working on a personal project of user check In/Out time recorder. I created the multi user login and time recorder using JS. I faced an issue to record the time of each logged in user. The code I created is only able to record the time of single user. I used localStorage command to store time because it need to be displayed every users time data on admin page. I am using single JS file for login, user page recorder and also for admin page loader. Plz help me out if anyone has any solution. I can't use server based code right now. I only have to write this web-app code in html,css and javascript.
var users= [
{user : 'user1', pass: 'pass1'},
{user : 'user2', pass: 'pass2'},
{user : 'user3', pass: 'pass3'},
{user : 'admin', pass: 'admin'}
];
function login()
{
//login page
var username = document.getElementById('uname').value;
var password = document.getElementById('psw').value;
for (var i = 0; i < users.length; i++)
{
console.log('enter the loop');
console.log("current user: ", i+1);
if (username == users[i].user && password == users[i].pass)
{
window.location.href = 'user.html';
alert("Login Successful");
break;
}
else if (i == (users.length-1))
{
alert('Login failed! Try Again');
console.log(i,'-times wrong');
}
else if (username == users[3].user && password == users[3].pass)
{
console.log('admin login');
window.location.href = 'admin.html';
break;
}
else
{
console.log('else statement');
}
}
var userId = i;
console.log("current user: ", userId);
}
//Date & Time Display
setInterval(myTimer,1000);
function myTimer()
{
const d = new Date();
document.getElementById('date').innerHTML = d.toLocaleDateString();
document.getElementById('time').innerHTML = d.toLocaleTimeString();
}
let date = document.getElementById('date');
let time = document.getElementById('time');
let newDate = new Date();
let year = newDate.getFullYear();
let month = newDate.getMonth();
let todaysDate = newDate.getDate();
let hours = newDate.getHours();
let minutes = newDate.getMinutes();
let seconds = newDate.getSeconds();
var cal = {
data : null,
sMth : 0,
sYear : 0,
init : () => {
let newDate = new Date();
cal.sDay = newDate.getDate();
cal.sMth = newDate.getMonth();
cal.hour = newDate.getHours();
cal.minutes = newDate.getMinutes();
cal.date = document.getElementById('date');
cal.data = localStorage.getItem("cal-" + cal.sDay + "-" + cal.sMth);
if (cal.data == null)
{
localStorage.setItem("cal-" + cal.sDay + "-" + cal.sMth, "{}");
cal.data = {};
console.log("cal.data: null-",cal.data);
}
else
{
cal.data = JSON.parse(cal.data);
console.log("cal.data: JSON-",cal.data);
}
},
checkIn : () => {
cal.data[cal.sDay] = cal.hour + ":" + cal.minutes;
localStorage.setItem('cal-${cal.sDay}-${cal.sMth}',JSON.stringify(cal.data));
console.log('Time:', cal.data);
}
}
window.onload = cal.init;

Google App Script problem in Loop emails when conversation length are long

Reference to the previous question to Filter Gmail body and paste in Spreadsheet
I had created below a google app script and set a trigger for after every 5 minutes:
function GetEmailsData(){
// SKIP TO OUT OF OFFICE HOURS AND DAYS
var nowH=new Date().getHours();
var nowD=new Date().getDay();
if (nowH>19||nowH<8||nowD==0) { return }
// START OPERATION
var Gmail = GmailApp;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var MasterSheet = ss.getSheetByName("Master");
var index = 2;
var aa = 0; // count already update entries
var na = 0; // count not update entries
var lasttime = MasterSheet.getRange("Z1").getValue(); // in spreadsheet i record the last time of email scanned, so next trigger will search after that
Logger.log(lasttime);
var cdate = new Date();
var ctime = cdate.getTime();
var qDate = MasterSheet.getRange("Z1").getValue();
Logger.log("QDATE IS " + qDate);
//problem # 1: from filter is not working.
// SEARCH EMAIL
var query = 'from: email id, subject: email subject, after:' + Math.floor((qDate.getTime()) /1000);
var threadsNew = Gmail.search(query);
Logger.log(threadsNew.length);
//loop all emails
for(var n in threadsNew){
var thdNew = threadsNew[n];
var msgsNew = thdNew.getMessages(); 
var msgNew = msgsNew[msgsNew.length-1];
// GET ATTACHMENT
//var bodyNew = msgNew.getBody();
var plainbody = msgNew.getPlainBody();
var subject = msgNew.getSubject();
var Etime = msgNew.getDate();
//var attachments = msgNew.getAttachments();
//var attachment = attachments[0];
Logger.log(Etime);
Logger.log(subject);
//Logger.log(plainbody);
var tdata = plainbody.trim();
var data = parseEmail001(tdata);
//Logger.log(data);
// First Check Email Date
var newdate = new Date();
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var yyyy = newdate.getFullYear();
var cd = dd + "-" + mm + "-" + yyyy
//Logger.log(new Date());
//Logger.log(cd);
if (Etime.getDate() != dd) {return}
// first check current sheet exist or not
// DATE DECLARATION IS ABOVE
var itt = ss.getSheetByName(cd);
if (!itt) {
ss.insertSheet(cd);
var itt = ss.getSheetByName(cd);
var ms = ss.getSheetByName("Master");
var hlc = ms.getLastColumn();
var headings = ms.getRange(1,1,1,hlc).getValues();
itt.getRange(1,1,1,hlc).setValues(headings);
}
var MasterSheet = ss.getSheetByName(cd);
var mlr = MasterSheet.getLastRow();
var mlc = MasterSheet.getLastColumn();
//check data already updated or not
var NewDepositSlipNumber = Number(data[2]).toFixed(0);
//Logger.log(Number(data[2]).toFixed(0));
var olddata = MasterSheet.getDataRange().getValues();
//Logger.log(olddata[1][2]);
for(var i = 0; i<olddata.length;i++){
if(olddata[i][2] == NewDepositSlipNumber){
//Logger.log(i + 1);
var status = 'Already Update'
Logger.log(status);
break;
}
else{
var status = 'Not Update'
//Logger.log(status);
}
}
// count how many updated and how many not.
if(status == 'Not Update'){
na = na + 1;
}
else{
aa = aa + 1;
}
if(status == 'Not Update'){
MasterSheet.appendRow(data);
Logger.log("Data Updated");
}
}
//problem # 2: if conversation length are long, it is not reaching there
var lastscantime = threadsNew[0].getLastMessageDate();
var master = ss.getSheetByName("Master");
master.getRange("Z1").setValue(lastscantime);
Logger.log(lastscantime);
master.getRange("Z2").setValue(new Date());
Logger.log(new Date());
Logger.log("Total " + threadsNew.length + " found, out of which " + aa + " are already updated, while " + na + " are updated.");
}
function parseEmail001(message) {
var replaces = [
'Branch Code',
'Branch Name',
'Slip No',
'BL Number',
'Type Of Payment',
'Customer Name',
'Payer Bank',
'Payer Bank Branch',
'Transaction Type',
'Amount',
'Posting Date',
'Value Date'
];
return message.split('\n').slice(0, replaces.length)
.map((c,i) => c.replace(replaces[i], '').trim());
}
This script is working fine but I have two problems:
I placed three filters in query 1) from 2) subject 3) after
but sometimes it gives me emails that are from the same ID but different subject.
as per my observation, and I verified it by using debug mode if the conversation length is long I guess more than 30 it will not reach the end part of the script. it skipping my last step as I also marked it in the above script. and if conversation length is less it works smoothly.
explanation: in other words, from morning to evening it's working fine after every five minutes, but the next day it gets the problem, then I manually update my spreadsheet master sheet Z1 value as of today's date and time, then it works fine till tonight.
You might be reaching a script limitation. Possibly the custom function runtime.But it can be any, you should see an error if it didn't finish.

Exception: Argument cannot be null: prompt Error in google Scripts

I have created a mail merge with a confirmation pop up in order to confirm the script has not been run recently, and also to double check the user intends to send emails. The script works perfectly, but annoyingly I receive the following error when run:
Stating; Exception: Argument cannot be null: prompt
I would like to get rid of this if possible. I attach my code.
//Creates a functional log of how many emails are sent and to how many branches
function confirmationWindow(){
var numberSent = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D3').getValue();
var numberOfVios = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D2').getValue();
var ui = SpreadsheetApp.getUi();
var ui = SpreadsheetApp.getUi();
ui.alert(
'You have succesfully sent ' + numberOfVios + ' violations, to ' + numberSent + ' branches.',)
}
function saveData() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Log');
var date = new Date()
var user = Session.getActiveUser().getEmail();
var range = ss.getRange("A:B")
var numberSent = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D2').getValue();
var branchNumber = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D3').getValue();
ss.appendRow([date,user,numberSent,branchNumber]);
}
var EMAIL_SENT = 'True';
function sendEmails() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Output');
var sheetI= SpreadsheetApp.getActive().getSheetByName('Input');
var sheetC = SpreadsheetApp.getActive().getSheetByName('Control');
var emailNum = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D3').getValue();
var startRow = 2;
var numRows = emailNum;
var dataRange = sheet.getRange(startRow, 1, numRows, 6);
sheetI.setTabColor("ff0000");
saveData()
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[3];
var message = row[5] + "\n\nT\n\nT\n\nT";
var message = message.replace(/\n/g, '<br>');
var subject = row[4];
MailApp.sendEmail(emailAddress, subject, message,{htmlBody:message});
sheet.getRange(startRow + i - 18, 8).setValue(EMAIL_SENT);
sheetC.getRange(startRow + i - 18, 3).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
confirmationWindow()
}
function recentSend() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Log');
var lastR = sheet.getLastRow();
var recentRun = sheet.getRange('A' + lastR).getValue();
if(lastR=1){var recentlySent = 'False'}
var today = new Date().valueOf()
var recentDate = recentRun
var sec = 1000;
var min = 60 * sec;
var hour = 60 * min;
var day = 24 * hour;
var difference = today - recentDate
var hourDifference =Math.floor(difference%day/hour);
if (hourDifference > '12'){var recentlySent = 'False'}
else {var recentlySent = 'True'}
return(recentlySent)
}
function recentlySentTrue(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Log');
var lastR = sheet.getLastRow();
var recentUser = sheet.getRange('B' + lastR).getValue();
var recentQuant = sheet.getRange('C' + lastR).getValue();
var recentT = sheet.getRange('A' + lastR).getValue();
var recentSendLog = recentT.toString();
var recentTime = recentSendLog.slice(16,21)
var recentDate = recentSendLog.slice(0,11)
var ui = SpreadsheetApp.getUi();
var result = ui.alert(
'Are you sure you wish to send?',
'The user, ' + recentUser + ' ,recently sent ' + recentQuant + ' emails, at ' + recentTime + ' on ' + recentDate,
ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
ui.alert(recentlySentFalse());
}
else {
}
}
function recentlySentFalse(){
var ui = SpreadsheetApp.getUi();
var ui = SpreadsheetApp.getUi();
var result = ui.alert(
'Are you Sure you wish to send?',
'Are you sure you want to send these violations?',
ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
ui.alert(sendEmails());
} else {
}
}
function confirm(){
var recentlySent = recentSend();
if (recentlySent == 'True'){
recentlySentTrue()
}
else{recentlySentFalse()
}
}
Any help would be great.
Explanation:
Your ui.alert() calls that have function arguments such as recentlySentFalse() are not valid, since the functions do not have return statements, hence they return the default value of null. ui.alert() calls need at least a prompt message.
Solution 1:
Put the function call after the UI alert message:
if (result == ui.Button.YES) {
ui.alert('Sending message...');
recentlySentFalse();
}
Solution 2:
If you do not want excessive alerts, just remove ui.alert and call the function immediately.
if (result == ui.Button.YES) {
recentlySentFalse();
}
References:
Class UI | Apps Script

Run Google script on single sheet instead of entire spreadsheet

With my spreadsheet, I have 2 Google forms tied to 2 sheets. When a form gets submitted the script executes and does it's thing. However, I only want the script to execute based on a submission from a single sheet. As it is now, the script executes when either of the forms get submitted.
My two sheets are:
Job Submission
and Order Submission
Any advice?
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
var printerId = "";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017","10/09/2017","11/23/2017","12/24/2017","12/25/2017","01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 );
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var order_count = values[2];
var order_form = values[7];
var print_services = values[3];
var priority = values[5];
var notes = values[6];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyOrderForm', order_form);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission - " + job_name;
var body = "Here is the work order for " + job_name + ". Job is due " + expirationDate + ".";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
var newDocName = docName + ' for ' + job_name;
return [copyId, newDocName];
}
function printGoogleDocument(copyId, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid" : "",
"content" : copyId,
"title" : docName,
"contentType" : "google.kix", // allows you to print google docs
"ticket" : JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(copyId, docName);
}
Edit:
I'm not sure how to do a complete or verifiable example since it's dependent on the form submission. I don't often work with javascript so I'm still learning.
Anyway, I updated my onFormSubmit function, however, my other functions have failed to execute. The script doesn't create the doc and in turn doesn't get sent to the google cloud print
// When Form Gets submitted
function onFormSubmit(e) {
// Initialize
var rng = e.range;
var sheet = rng.getSheet();
var name = sheet.getName();
// If the response was not submitted to the right sheet, exit.
if(name != "Job Submission") return;
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(copyId, docName);
}
If your onFormSubmit function is on a script bounded to the spreadsheet, the event object includes a range object. You could use getSheet to get the sheet and then getName to get the sheet name.
Example:
function onFormSubmit(e){
// Initialize
var rng = e.range;
var sheet = rng.getSheet();
var name = sheet.getName();
// If the response was not submitted to the right sheet, exit.
if(name != "Responses 1") return;
//Otherwise continue
}
Going off of Ruben's suggestion, here is what I ended up with
function onFormSubmit(e) {
// Initialize
var name = e.range.getSheet().getName();
// If the response was not submitted to the right sheet, exit.
if (name != "Job Submission") return;
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName = returnedDocValues[1];
printGoogleDocument(copyId, docName);
}

Categories