Modify a cell in Google Sheet using Google App Script - javascript

I am a beginner in google app script. I am creating a resident payment system where the user can change their password upon logging in. So now, I have done the html part for changing the password but I dont know how to do the coding in order to change the password. I have attached some pictures and my code to explain myself better. Thank you so much guys.
https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1775459006 - Link to google sheet
https://script.google.com/macros/s/AKfycbw_A-XRlXtR9qGNvMKVrorMIg71hwHt0DrHRiNGVYZdURbadYgUtOIkJPsvuYsBK7Fe/exec - Link to Web App
https://script.google.com/d/1DdRKqUX__-ZITUgTZanQ_A7hUL1kcc0TZOeFmn58wYsX_o_7cqNExnYo/edit?usp=sharing - Link to app script
Code for Code.gs
var url = "https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1775459006";
var streetSheetName = "JALAN SANGGUL 4";
function doGet(e) {
var streetSheetName = "JALAN SANGGUL 4"; // Added
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
return HtmlService.createHtmlOutputFromFile('WebAppLogin');
}
function checkLogin(username, password) {
var found_record = '';
var name = '';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("USERNAMES");
var getLastRow = webAppSheet.getLastRow();
for(var i = 2; i <= getLastRow; i++) {
if(webAppSheet.getRange(i, 1).getValue().toUpperCase() == username.toUpperCase() && webAppSheet.getRange(i, 7).getValue() == password) {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
} else if (username.toUpperCase() == 'ADMIN' && password == 'ADMINPASSWORD') {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
}
}
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
if(found_record == '') {
found_record = 'FALSE';
}
return [found_record, username,name];
}
function GetRecords(username,filter) {
var filteredDataRangeValues = GetUsernameAssociatedProperties(username);
var resultArray = GetPaymentRecords(filteredDataRangeValues,filter);
return resultArray;
}
function GetUsernameAssociatedProperties(username) {
var filteredDataRangeValues = '';
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName("USERNAMES");
var dataRangeValues = displaySheet.getDataRange().getValues();
if (username.toUpperCase() == 'ADMIN') {
dataRangeValues.shift();
filteredDataRangeValues = dataRangeValues;
} else {
filteredDataRangeValues = dataRangeValues.filter(row => row[0].toUpperCase() == username.toUpperCase());
}
return filteredDataRangeValues;
}
function GetPaymentRecords(userProperties,filter) {
var streetSheetName = PropertiesService.getScriptProperties().getProperty("streetSheetName"); // Added
var transpose = m => m[0].map((_, i) => m.map(x => x[i]));
var resultArray = [];
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName(streetSheetName);
var addressValues = displaySheet.getRange("B:C").getValues();
var paidMonthValues = displaySheet.getRange(1, 7, displaySheet.getLastRow(), displaySheet.getLastColumn() - 6).getValues();
//Logger.log(addressValues);
//Logger.log(transpose(paidMonthValues));
userProperties.forEach((v, i) => {
var userHouseNumber = v[1];
var userStreet = v[2];
var column = addressValues.reduce(function callbackFn(accumulator, currentValue, index, array) {
if (currentValue[0] == userHouseNumber && currentValue[1] == userStreet) {
return index
} else {
return accumulator
}
}, '');
//Logger.log(column);
Logger.log(filter)
Logger.log(paidMonthValues);
if(filter=="None"){
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}else{
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
if(element[0].includes(filter))return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}
resultArray = resultArray.concat(result);
//Logger.log(resultArray);
})
//Remove null elements
resultArray = resultArray.filter(element=>{
Logger.log(element!=null)
return element != null;
});
return resultArray;
}
Code for WebAppLogin.html
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
google.script.run
.withSuccessHandler(updateButton)
.getEmail()
alert('Password changed');
}

I believe your goal as follows.
When the button of "Change Password" is clicked and input the value and click "Save changes", you want to change the password in the Spreadsheet.
Modification points:
In your script, when "Save changes" button is clicked, it seems that google.script.run.withSuccessHandler(updateButton).getEmail() is run. But, unfortunately, in your script, there are no functions of updateButton and getEmail. By this, an error occurs.
When I saw your shared sample Spreadsheet, it seems that your sample Spreadsheet is different from the sample Spreadsheet of your image. For example, the column "A" of the sheet "USERNAMES" is different. In your shared Spreadsheet, the column "A" is 4.
From this situation, from your replying of it just the same you can notice it now yesterday I mistaken changed it in to 4 sorry about that., I understood that the column "A" of the sheet "USERNAMES" is "USERNAME".
About updateButton, in this answer, alert('Password changed') is run as the sample.
In order to update the password of Spreadsheet, it is required to use the username and the inputted password. And, it is also required to prepare the function at Google Apps Script side.
When above points are reflected to your script, it becomes as follows.
Javascript side:
From:
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
To:
var username = ""; // Added
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
username = document.getElementById("username").value; // Modified
var password = document.getElementById("password").value;
And, please modify changePassword() as follows.
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
var newPassword = document.getElementById("newPassword").value;
google.script.run.withSuccessHandler(() => alert('Password changed')).changePassword(username, newPassword);
}
}
Google Apps Script side:
Please add the following function to Google Apps Script side.
function changePassword(username, newPassword) {
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("USERNAMES");
var range = sheet.getRange("A2:A").createTextFinder(username).matchEntireCell(true).findNext();
if (range) {
range.offset(0, 6).setValue(newPassword);
}
}
Note:
In this case, when the password is changed, the alert of "Password changed" can be seen. And, the column "G" of Sheet "USERNAMES" is changed.

Related

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

SyntaxError: missing ) after argument list (line 28, file "Code.gs")

i am working on google apps script and i have come across an error which i cannot resolve.
the error occurs at the end on this line return ContentService.createTextOutput("thankyou...
I can't figure out the error. please assist me.
below is the full code
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1CIdq1anGwzUrfrNNd08NtgTR-QeHUDHgb4HOlnobmkk/edit#gid=0");
var sheet = ss.getSheetByName("Examiners");
function doGet(e){
var action = e.parameter.action;
if(action == "in")
return verified(e);
}
function doPost(e){
var action = e.parameter.action;
if(action == "in")
return verified(e);
}
function verified(e){
var id = e.parameter.id;
var values = sheet.getRange(2,1,sheet.getLastRow(),1).getValues();
for(var i = 0 ; i<values.length ; i++){
if(values[i][0] == id){
i=i+2;
var verified = Utilities.formatDate(new Date(), "EAT", "HH:mm:ss");
sheet.getRange(i,3).setValue(verified);
var fullname = sheet.getRange(i,2).getValue();
return ContentService.createTextOutput("Thank You" (fullname)"is verified at" (verified)).setMimeType(ContentService.MimeType.TEXT);
}
}
}
return ContentService.createTextOutput("Id Not Found").setMimeType(ContentService.MimeType.TEXT);
}
There were a few errors in your styling, one was how you concated strings. You used: "Thank You" (fullname)"is verified at" (verified), however this is a syntax error, as you need a + to conact several variables/strings to a string or use a template string, you got two options:
Using +: "Thank You " + fullname + " is verified at " + verified
Using template strings (Note: those are not done in quotation marks but in backticks): `Thank You ${fullname} is verified at ${verified}`
This is what I think how you mean, but I'm unsure about the last return as it was placed outside any function, I just but it one line up in the last function:
var sheet = ss.getSheetByName("Examiners");
function doGet(e) {
var action = e.parameter.action;
if (action == "in")
return verified(e);
}
function doPost(e) {
var action = e.parameter.action;
if (action == "in")
return verified(e);
}
function verified(e) {
var id = e.parameter.id;
var values = sheet.getRange(2, 1, sheet.getLastRow(), 1).getValues();
for (var i = 0; i < values.length; i++) {
if (values[i][0] == id) {
i = i + 2;
var verified = Utilities.formatDate(new Date(), "EAT", "HH:mm:ss");
sheet.getRange(i, 3).setValue(verified);
var fullname = sheet.getRange(i, 2).getValue();
return ContentService.createTextOutput("Thank You" + fullname + "is verified at" + verified).setMimeType(ContentService.MimeType.TEXT);
}
}
return ContentService.createTextOutput("Id Not Found").setMimeType(ContentService.MimeType.TEXT);
}
Furthermore I suggest you format your code better. Do you use an Editor? Many Editors can auto-format you your code, which makes it much more readable
Replace
return ContentService.createTextOutput("Thank You" (fullname)"is verified at" (verified)).setMimeType(ContentService.MimeType.TEXT);
by
return ContentService.createTextOutput("Thank You" + fullname + "is verified at" + verified ).setMimeType(ContentService.MimeType.TEXT);
Resources
Handling text — strings in JavaScript

Javascript call back function not working as expected. Trying to make sure all code is complete before the finalization logic is executed

I am trying to have a summary section in my website that will take all the results from other functions and display the information. I created the following functions and call path to try and get this but it appears that the callback is still being called before the largest function finishes.
Office.onReady(info => {
if (info.host === Office.HostType.Outlook) {
document.getElementById("app-body").style.display = "flex";
mainprocessing(finalization);
}
});
function mainprocessing(callback){
console.log("main processing")
reviewEmailInfo();
attachmentCheck();
checkBodyforLinks();
checkmsgforriskywords();
callback();
}
function finalization(){
console.log("entering finalization");
document.getElementById("riskscore").innerHTML = "This email has a riskscore of " + riskScore;
}
I put console.logs into each function at the beginning and end and this is what is in the logs
main processing taskpane.js:43
entering review email taskpane.js:122
entering attachment check taskpane.js:137
leaving attachment check taskpane.js:174
entering check body taskpane.js:192
leaving check body taskpane.js:196
entering check risky words taskpane.js:210
entering leaving check risky taskpane.js:38
entering finalization VM72 taskpane.js:9931
leaving review email VM72 taskpane.js:9002
[WDS] Live Reloading enabled.client:52
[WDS] Live Reloading enabled.
leaving review email taskpane.js:106
function checkBodyforLinks(){
console.log("entering check body");
Office.context.mailbox.item.body.getAsync(
"html",
{ asyncContext: "This is passed to the callback" },
function callback(result) {
var parser = new DOMParser();
var bodyHtml = parser.parseFromString(result.value, "text/html");
//need to add check to ignore mailto: links
var linkDomains = [], links = bodyHtml.links;
document.getElementById("linkCheck").innerHTML = "No links found within email body";
for (var i = 0; i < links.length; i++){
linkDomains.push(links[i].href);
}
if (linkDomains.length > 0){
document.getElementById("linkCheck").innerHTML = "There are " + links.length+1 +"links in the email body";
}
}
);
console.log("leaving check body");
}
console.log("entering review email");
Office.context.mailbox.item.getAllInternetHeadersAsync(
function(asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
var headers = asyncResult.value;
var ReplyTo = headers.replace(" ","").match(/Return-Path:(.*)/);
if (ReplyTo.length != null){
var cleanEmail = ReplyTo[1].substring(1,ReplyTo[1].length);
if(cleanEmail == Office.context.mailbox.item.sender.emailAddress){
document.getElementById("reply-match").innerHTML= "The from and reply email address match";
}else{
riskScore += 5;
document.getElementById("reply-match").innerHTML= "The from and reply email address DO NOT MATCH. The sender is:" + Office.context.mailbox.item.sender.emailAddress + " and the reply addres is: " + cleanEmail;
}
}
var ARCAuthResult = headers.replace(" ","").match(/ARC-Authentication-Results:(.*)/);
var dkimChk = false;
var spfChk = false;
if(ARCAuthResult != null){
if(ARCAuthResult[1].search("spf=pass")){
spfChk = true;
}
if(ARCAuthResult[1].search("dkim=pass")){
dkimChk = true;
}
}else{
var AuthResult = headers.replace(" ","").match(/Authentication-Results:(.*)/);
if(AuthResult.length != null){
if(AuthResult[1].search("spf=pass")){
spfChk = true;
}
if(AuthResult[1].search("dkim=pass")){
dkimChk = true;
}}}
if(spfChk == true & dkimChk==true){
document.getElementById("dkimspfchk").innerHTML = "Both DKIM and SPF are safe";
}else if(spfChk == true){
riskScore += 5;
document.getElementById("dkimspfchk").innerHTML = "DKIM check failed";
}else if(dkimChk == true){
riskScore += 5;
document.getElementById("dkimspfchk").innerHTML = "SPF check failed";
}else{
riskScore += 10;
document.getElementById("dkimspfchk").innerHTML = "SPF amd DKIM check failed";
}
//Check for domain match between sender and reciever
var domainIndex = Office.context.mailbox.item.sender.emailAddress.indexOf("#");
var senderDomain = Office.context.mailbox.item.sender.emailAddress.slice((domainIndex+1), Office.context.mailbox.item.sender.emailAddress.length);
var receiverAddress = headers.replace(" ","").match(/To:(.*)/);
if (receiverAddress.length != null){
domainIndex = receiverAddress[1].indexOf("#");
var recieverDomain = receiverAddress.slice((domainIndex+1),receiverAddress.length-1);
if(senderDomain == recieverDomain){
document.getElementById("domainMatch").innerHTML = "This email comes from with your domain";
}else {
riskScore += 1;
document.getElementById("domainMatch").innerHTML = "This message comes from an external email address";
console.log("risk score after domain " + riskScore);
}
}
//var domainAge = domainWhois(senderDomain);
console.log("leaving review email");
return;
} else {
if (asyncResult.error.code == 9020) {
// GenericResponseError returned when there is no context.
// Treat as no context.
} else {
console.log("error");
}
}
}
);
return;
}

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);
}

Making an ajax request with jsonp(no jquery)

I need some help on an assignment that I need to do. Basically the question is a number guessing game. We're assigned a number in the interval [0,1023] based on our student number and we have 11 guesses to get the right number. I know I have to use a binary search to get the number, my only problem is connecting to the server and getting a result.
We're given this:
A sample request looks as follows:
http://142.132.145.50/A3Server/NumberGuess?snum=1234567&callback=processResult&guess=800
And also given that the request returns the following parameters:
1: A code to determine if your guess is equal, less than or greater than the number
2: Message string
3: Number of guesses made by my application
This is what I've tried so far, just as a test to get the server request working. All I get in return is "object HTMLHeadingElement"
window.onload = function() {
newGuess();
}
function newGuess() {
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess=600";
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(code,message,guesses) {
var code = document.getElementById("code");
var message = document.getElementById("message");
var guesses = document.getElementById("guesses");
code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
}
EDIT: Current state of my code.
window.onload = function() {
min = 0;
max = 1023;
mid = 0;
setInterval(newGuess,1000);
};
function newGuess() {
mid = Math.floor((max-min)/2);
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess="+mid;
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(codeJ,messageJ,guessesJ) {
code = document.getElementById("code");
message = document.getElementById("message");
guesses = document.getElementById("guesses");
code.innerHTML = codeJ;
message.innerHTML = messageJ;
guesses.innerHTML = guessesJ;
if(codeJ == 0){
return;
}else if(codeJ == -1){
min = mid + 1;
}else if(codeJ == 1){
max = mid -1;
}
console.log(mid);
}
Check your variable-names. You are overwriting the function-patameters.
Something like
code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
just CAN'T work, you should see the problem yourself...

Categories