How to display multiple choice grid from google forms using apps script - google-apps-script

I have a google form with a multiple choice grid question:
Status
Ok Bad Work Cancel
Category1 * * * *
Category2 * * * *
I need to use the apps script to display the values for each category in the work messenger
Where did I go wrong please help
This is my code, I tried to display specific statuses in this way (I am attaching part of the code)
`if(payload["Status [Category1]"]) {
status_cat1 = "Category1: " + payload[Status [Category1]] + " ";
} else {
status_cat1 = ""
}
if(payload["Status [Category2]"]) {
status_cat2 = "Category2: " + payload["Status [Category2]"] + " ";
} else {
status_cat2 = ""
}
var text = status_cat1 + status_cat2`
It displays undefined, but I choose the statuses

Related

How to program a URL? (For search query)

A co-worker of mine shared an autohotkey script (it's actually an exe file that runs on the background). Anyways, when I click the hotkeys it opens up a company webiste and creates a shared query for whatever's on the clipboard. I was wondering how this is done and how I can make my own.
I'm specially curious about the "URL" modification that includes all these search options:
https://<COMPANYWEBSITE>/GotoDocumentSearch.do
That's the URL where I can search (sorry it's restricted and even if I link it you cant access it).
Anyways, after I set up all my options and stuff and click the search button I get the following URL:
https://<COMPANYWEBSITE>/DocumentSearch.do
I inspected the website source and this is the function that's called when I press the search button:
function preSubmitSearch(docPress) {
document.pressed = docPress;
// setup local doc types for submit by lopping over multi selects and building json data string
var localDocTypesJson = "{";
var sep = "";
jQuery(".localTypeSel").each(function (i) {
var selLocalTypes = jQuery(this).multiselect("getChecked");
// get doc type code from id ex. 'localTypeSel_PD'
//window.console.log("this.id=" + this.id);
var tmpArr = this.id.split("_");
var docTypeCode = tmpArr[1];
var selLocalTypesCnt = selLocalTypes.length;
if (selLocalTypesCnt > 0) {
var localTypes = "";
var sep2 = "";
for (var i2 = 0; i2 < selLocalTypesCnt; i2++) {
localTypes += sep2 + "\"" + selLocalTypes[i2].value + "\"";
sep2 = ",";
}
localDocTypesJson += sep + "\"" + docTypeCode + "\": [" + localTypes + "]";
sep = ",";
}
});
localDocTypesJson += "}";
jQuery("#localDocTypesJson").val(localDocTypesJson);
}
HOWEVER, the working code that was shared with me (that was written ages ago by some employee who's not here anymore). Has the following URL when I use the autohotkey:
https://<COMPANYWEBSITE>/DocumentSearch.do?searchType=all&localDocTypesJson=7D&formAction=search&formInitialized=true&searchResultsView=default&btn_search=Search&docName=*<CLIPBOARD>*&wildcards=on&docRevision=&latestRevOnly=true&docProjectNumber=&docEngChangeOrder=&docLocation=&findLimit=500&docTypes=Customer+Drawing&docTypes=Production+Drawing&docTypes=Manufacturing+Process+Document&docTypes=Specification+Or+Standard
Note: replaced text with "CLIPBOARD" for clarification.
I was wondering if that's a type of "URL-programming" or how can I make a direct URL that prompts for the search results from the website? is that Javascript? or how is that programmed? (I know Swift and some Java, but have never really used Javascript).
It doesn't seem like you are asking an AutoHotKey (AHK) question, but to give you an AHK example you can copy, here is how I would use AHK to use Google.com to search for whatever is in my clipboard:
wb := ComObjCreate("InternetExplorer.Application")
wb.Visible := true
wb.Navigate("https://www.google.com/search?q=" . StrReplace(Clipboard, " ", "+") . "", "")
Note, the URL format includes the query ("?q=whatever+you+had+in+Clipboard") in it with spaces replaced by "+"s.
Hth,

How do I get output to the webpage while still inside a cfscript?

Sorry for the longer post, I'm trying to be specific. I'm a bit of a newb at cold fusion and lucee, so forgive me if I have missed something fundamental here. I'm just trying to do a quick POC, but can't get it working. What I am trying to do is make a page call, write to a web page, sleep for a while. Kind of a heartbeat. What I can't get to happen is the write to the web page...until all sleep(s) have happened and the page cfm file completes processing. I've looked extensively for the past couple of days, and have tried numerous items, but to no avail. From my index.cfm lucee page, I have a link to launch a new tab and call my cfm file.
<a href="./pinger2.cfm" target="_blank"><img class="ploverride" src="/assets/img/Ping.png" alt="Ping Test" width="125" height="75">
No problem here, a new tab opens and pinger2.cfm starts processing.
What I'm hoping for is the table heading to almost immediately print to the page, then make the first call out, print the results to the page, sleep, make the next call out, print to the page...but it no workey. Anyone have a clue? The code in the pinger2.cfm file is:
<cfscript>
public struct function pinger( required string url, required string verb, required numeric timeout, struct body )
{
var result = {
success = false,
errorMessage = ""
};
var httpService = new http();
httpService.setMethod( arguments.verb );
httpService.setUrl( arguments.url );
httpService.setTimeout( arguments.timeout );
if( arguments.verb == "post" || arguments.verb == "put" )
{
httpService.addParam(type="body", value=SerializeJSON(arguments.body));
}
try {
callStart = getTickCount();
var resultObject = httpService.send().getPrefix();
callEnd = getTickCount();
callLength = (callEnd-callStart)/1000;
if( isDefined("resultObject.status_code") && resultObject.status_code == 200 )
{
result.success = true;
logMessage = "Pinger took " & toString( callLength ) & " seconds.";
outLine = "<tr><td>" & resultObject.charset & "</td><td>" & resultObject.http_version & "</td><td>" & resultObject.mimetype & "</td><td>" & resultObject.status_code & "</td><td>" & resultObject.status_text & "</td><td>" & resultObject.statuscode & "</td><td>" & logMessage & "</td></tr>";
writeOutput( outLine );
getPageContext().getOut().flush();
return result;
}
else
{
throw("Status Code returned " & resultObject.status_code);
}
}
catch(Any e) {
// something went wrong with the request
writeDump( e );
abort;
}
}
outLine = "<table><tr><th>charset</th> <th>http_version</th> <th>mimetype</th> <th>status_code</th> <th>status_text</th> <th>statuscode</th> <th>time</th> </tr>";
writeOutput( outLine );
getPageContext().getOut().flush();
intCounter = 0;
while(intCounter LT 2)
{
theResponse = pinger(
url = "https://www.google.com",
verb = "GET",
timeout = 5
);
intCounter = intCounter + 1;
getPageContext().getOut().flush();
sleep(2000);
}
outLine = "</table>";
writeOutput( outLine );
</cfscript>
NOTE: I'm sure there are other "less than best" practices in there, but I'm just trying to do this quick and dirty.
I thought the getPageContext().getOut().flush(); would do the trick, but no bueno.
EDIT: If it matters, I'm using CF version 10,0,0,0 and Lucee version 4.5.2.018.
I do something similar to generate ETags by hand (using Lucee 4.5). I stick a simple
GetPageContext().getOut().getString()
in the onRequestEnd function in Application.cfc. This returns a string of HTML just like it's sent to the browser.
You could store that in the appropriate scope (APPLICATION, SESSION, etc) and use it later, or whatever you need. Obviously, all processing needs to be completed, but it shouldn't require any flushes. In fact, flushing may or may not alter its behavior.

Trouble Adding Array output to an Dynamically Generated HTML String in GAS Google Script

I am trying to automate my businesses blog. I want to create a dynamic html string to use as a wordpress blog description. I am pulling text data from email body's in my gmail account to use as information. I parse the email body using the first function below.
I have everything working properly except for the for loop (in the second code block) creating the description of the post. I have searched for hours and tried dozens of different techniques but I cant figure it out for the life of me.
Here is how I am reading the text values into an array:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
This is how I am trying to dynamically output the text arrays to create a basic HTML blogpost description (which I pass to xmlrpc to post):
var1 = getMatches(string, regex expression, 1);
var2 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var fulldesc = "<center>";
var text = "";
for (var k=0; k<var1.length; k++) {
text = "<u><b>Var 1:</u></b> " + var1[k] + ", <u><b>Var 2:</u></b> " + var2[k] + ", <u><b>Var 3:</u></b> " + var3[k] + ", <u><b>Var 4:</u></b> " + var4[k] + ", <br><br>";
fulldesc += text;
}
fulldesc += "</center>";
Lastly here is the blog post description code (using GAS XMLRPC library):
var fullBlog = "<b><u>Headline:</u> " + sub + "</b><br><br>" + fulldesc + "<br><br>General Description: " + desc;
var blogPost = {
post_type: 'post',
post_status: 'publish', // Set to draft or publish
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
categories: cat, //cat is defined elsewhere and works fine
date_created_gmt: pubdate2, //defined elsewhere (not working but thats another topic)
mt_allow_comments: 'closed',
description: fullBlog
};
request.addParam(blogPost);
If there's only one value in the var1,2,3,4 arrays all works as it should. But any more than 1 value and I get no output at all from the "fulldesc" var. All other text variables work as they should and the blog still gets posted (just minus some very important information). I'm pretty sure the problem lies in my for loop which adds the HTML description to text var.
Any suggestions would be greatly appreciated, I'm burned out trying to get the answer! I am a self taught programmer (just from reading this forum) so please go easy on me if I missed something stupid :)
Figured it out: It wasnt the html/text loop at all. My blogpost title had to be a variable or text, but not both.
Not working:
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
Working:
var test = 'Ticker: ' + sub;
//
title:test,

Output from an array in html page

I am trying to output the contents of an array within an array to a small area on an HTML page. I can only get one dimensional arrays to output.
Simplified, the intended array has a number of properties, but am struggling to find the correct code to output an array nested inside an array.
Properties are;
ID(integer)
Location(string)
Postcode(String)
other properties may be added down the line.
To output the information I am using the following code (which I can only get to work on a single array - even if I change to using [i][x] )
document.write("<tr><td>ID " + i + " is:</td>");
document.write("<td>" + LocationArray[i] + "</td></tr>");
How do I correctly create an array capable of storing the information and then output a specific part of it? eg display the contents of LocationArray[2][3]
Is document.write an efficient method, or is there something better?
I put something together, that could help you. To answer your question at the end about creating an array 'the right way'; There are two possibilities:
Create an array with 'property'-based properties : var locationsArray = [{ID:123,Location:'blabla',Postalcode:'1234'}];
Create an array with string-keys : var locationsArray = [{'ID':123,'Location':'blabla','Postalcode':'1234'}];
In my example I used the first attempt.
To your second question: document.write just writes at the end of the document. If you want to write to a specific area of the website, create a container (for example) and give it an id. Then change the property innerHTML of the created container, as I did in my example.
HTML:
<div id="locations"></div>
<button onclick="printLocations()">Print Locations</button>
Javascript:
function printLocations() {
var locationsArray = [{
ID : 123,
Location : 'Candyland',
Postalcode : '1234'
}, {
ID : 456,
Location : 'Middle-Earth',
Postalcode : '4567'
}
];
var locationsHtml = '';
for (var index in locationsArray) {
locationsHtml += 'ID: ' + locationsArray[index].ID + ', ' +
'Location: ' + locationsArray[index].Location + ', ' +
'Postalcode: ' + locationsArray[index].Postalcode + '<br />';
}
console.log(locationsHtml);
document.getElementById('locations').innerHTML = locationsHtml;
}
If you just want to write a specific part of the array (in your example just one specific location) just use the index you want and access it the same way as in the for loop in my example:
var locationsHtml = locationsArray[1].ID + locationsArray[1].Location + etc...;
/*with string-keys: var locationsHtml = locationsArray[1]['ID'] + etc...;*/
document.getElementById('locations').innerHTML = locationsHtml;

"CalendarApp: Mismatch: etags" when adding reminders - Google Apps Scripts

I have a small Google Apps Script that processes a date column in a spreadsheet and generates entries in a Calendar (birthdays).
Work is fine, but when adding reminders to the (recently-created) CalendarEvent, an error is thrown :
Service error: CalendarApp: Mismatch: etags = ["GUQKRgBAfip7JGA6WhJb"], version = [63489901413]
I've tried to perform 1 second sleep after creating event (wait for changes to be done in calendar), but no luck on this...
BTW, events are created succesfully, only reminders cannot be added.
PD: the calendar is one I own, but not my primary calendar.
Here is part of the code:
try
{
birthday = new Date(Data[i][BirthColumn]);
birthday.setFullYear(today.getFullYear());
birthday.setUTCHours(12);
birthlist += Data[i][NameColumn] + " --> " + birthday + "\n";
calendarevent = cal.createAllDayEventSeries("¡Cumpleaños " + Data[i][NameColumn] + "!", birthday, CalendarApp.newRecurrence().addYearlyRule().times(YearsInAdvance));
if (calendarevent == null)
success = false;
else
{
//This sentence fails every single time.
calendarevent.addEmailReminder(0);
calendarevent.addPopupReminder(0);
calendarevent.addSmsReminder(0);
}
}
catch (ee)
{
var row = i + 1;
success = false;
errlist += "Error on row " + row + ": check name and birth date. Exception Error: " + ee.message + "\n";
}
This is the portion of the code I finally change to make it work, as Serge insas suggest me before:
if (calendarevent == null)
success = false;
else
{
cal.getEventSeriesById(calendarevent.getId()).addEmailReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addPopupReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addSmsReminder(0);
}
This is a known issue
See comment nr 67 for a working workaround : the trick is to re-call the event for every item you want to add (reminder, popup...) using cal.getEventSeriesById(eventID) after you get the Id simply with .getId()
I use it in some scripts and it solved the issue for me.