Fire a POST Request using Google Sheets (on Form Submit) - google-apps-script

I used a Google Sheet form as a newsletter registration form.
In the response form i've built a Formula which builts the request.
Column A has a timestamp
Column B the e-mail adress
Column C builts the request:
Example Output
http://newsletter.request.com/automated/action.jsp?action=SubscribetoNL&pw=XXX&email=xx#xx.com
Is there a way to have a script fire (click on or use POST) the newly created request on form submit?
thanks a lot for your help!

Well, you can not fire POST request on Form submit, but you can use of trigger functionality. You can set a trigger which is executed as soon as the form is submitted submitted. As soon as form is submitted, your custom function will fire, you can do something like this in that function,
var url = UrlFetchApp.fetch('http://newsletter.request.com/automated/action.jsp?action=SubscribetoNL&pw=XXX&email=xx#xx.com');
var responseCode = url.getResponseCode();
if(responseCode == 200) {
//do your own stuff
} else {
//do your own thing
}
Currently, doPost() is only available for standalone web apps. Refer this help article about doPost() and doGet().

Related

Fetch the data that was submitted in the google form (using OnFormSubmit trigger) with apps script

I created an apps script project for my google form, and added a trigger which has the following settigs -
and my Code.gs file has this code, which is supposed to execute when a new submission arrives -
function sendemail(e) {
GmailApp.sendEmail("sampleemail#gmail.com","Hello there","This is a sample sentence.");
}
When I tested this trigger by submitting a new form, I received the test email successfully. Now instead of a static email (sampleemail#gmail.com) being used as the recipient of the email, I want it to be the value my user entered in the Email field in the form submission which triggered this function. So I want my code to look like -
function sendemail(e) {
GmailApp.sendEmail("<email from form response>","Hello <name from the form>","This is a sample sentence.");
}
So if the trigger data is arriving in the e parameter in sendemail function, how do I get the data which was submitted? When I debugged JSON.stringify(e), I get {"authMode":"FULL","response":{},"source":{},"triggerUid":"12647267"}.
Is there any way I get the data that was submitted in the form in the function? Do I need to change any settings on my form or trigger to get the data? I've just started with Google Apps Script and am a bit confused on how should I do this... Any advice is appreciated! Thanks :)
Solution by #Cooper in the comments
Try using the onFormSubmit trigger for the linked Spreadsheet. It;s event object contains namedValues and values.
Thanks #Cooper, it works perfectly now. Cheers!

Send an email response when a Google form is filled during specific working hours

We have requests / tickets coming across teams which are in different countries. And these requests are submitted through Google Forms. These requests / tickets are then picked at a single location and processed
There's a 5 hour non working window from 00:00 am to 5am. During this time as well we do get requests from the offices.
Is there a way if a form is submitted during this non workings hours an email notification goes to the requester letting them know that we are closed and the request submitted will be picked once we are open?
There is an option to run script. But i get an error.
If a script has to be run, how would that be possible based on the requirement?
Thanks
You can use the onFormSubmit trigger for spreadsheets. It provides all of the information for each submission via namedValues which is an object or values which is an array. As an installable trigger it is capable of performing operations that require permission like sending emails.
onFormSubmit event object
There are many examples of doing this on this site.
You will encounter such error when you tried to run your code manually using the Script Editor because your event object doesn't exist.
I tried to run your code using an on-form submit in Google Form itself and it was triggered successfully when I submit a form as an example. Google Forms events - Form submit
Using on-form submit installable trigger in Google Forms:
Sample Code:
function sendEmail(e) {
//response //getRespondentEmail()
var html = HtmlService.createTemplateFromFile("email.html");
var htmlText = html.evaluate().getContent();
//logger.log(htmlText);
var emailTo = e.response.getRespondentEmail();
var subject = "Thanks for filling the form";
var textBody = "This email requires HTML support make sure you opn";
var options ={ htmlBody: htmlText };
var today = new Date();
Logger.log(today.getHours())
if (emailTo !== undefined && today.getHours() < 5){
GmailApp.sendEmail(emailTo, subject, textBody, options);
}
}
Modifications done:
I just include an additional condition to check for the current time when the form was submitted to check if it is within 00:00 to 05:00. Refer to JavaScript getHours() Method
In this sample code, the email will only be sent when a form was submitted from 00:00 to 04:59. You can adjust the condition based on your preference if you want. You can also include checking the minutes using JavaScript getMinutes() Method
Note:
You can debug your installable triggers by adding logs in your code and by checking the Executions tab in the Apps Script Editor.

Wrong source and response in form triggers

I set a simple workflow with a Google Apps Script. I created the script project from a form A.
Here is the workflow:
users submit a response for the form A
the script creates a new response for the form B, submit it, and sends me the edition link by email
I submit the response for the form B the script created for me
the script sends me a recap of both form by email
To do so I have programmatically set up a trigger on the form B:
function addOnNewFormBSubmitTrigger() {
ScriptApp.newTrigger('onNewFormBSubmit')
.forForm(FORM_B_ID)
.onFormSubmit()
.create();
}
The function onNewFormBSubmit looks like that:
function onNewFormBSubmit(formSubmitEvent) {
_sendAnalysisEmail(formSubmitEvent.source, formSubmitEvent.response);
}
The function is triggered but the the formSubmitEvent.source value is the form A and formSubmitEvent.response is the latest response for this form. I would expect the source to be the form B, as I attached the trigger on it.
EDIT:
Even passing a form instance instead of its ID does not work as I expect it
function addOnNewAlaysisSubmitTrigger() {
var form = FormApp.openById(FORM_B_ID);
ScriptApp.newTrigger('onNewFormBSubmit')
.forForm(form)
.onFormSubmit()
.create();
}
Am I missing something?
Thank you #tehhowch, the link you gave me in the comments made me think that it may work if the script is not created from the Form. Thus I made a POC creating the script from a Spreadsheet and it works.
This is the script I made: Google Apps Script
And these are the logs generated by the two functions: function call logs from Stackdriver
As you can see I get two different responses submitted from the two forms.
Now the problem is that the event is not a submit form event as defined in the documentation: https://developers.google.com/apps-script/guides/triggers/events#form-submit_4 but this is another story.
If you want to try, here are:
the spreadsheet from where I created the forms and the script (logs are pushed in the "logs" sheet): https://docs.google.com/spreadsheets/d/17pFDXlYpOjXgaN5ZsBYimrBZHl6WPcmUvMrAjAnc9ys/edit?usp=sharing
the live form A (Google sign in required): https://docs.google.com/forms/d/e/1FAIpQLSff7ISYkqLtPwtzTWw2Iwxmm4dIax7z9ye9EeLY9SxDz3vJvw/viewform?usp=sf_link
the live form B (Google sign in required too): https://docs.google.com/forms/d/e/1FAIpQLSc1HrswTr6prGxBBwy2a4Nqs1pyF7CJTjk2HafZyXsTtdnaXQ/viewform?usp=sf_link
the script : https://docs.google.com/spreadsheets/d/17pFDXlYpOjXgaN5ZsBYimrBZHl6WPcmUvMrAjAnc9ys/edit?usp=sharing
Have you tried to use Form as parameter instead of just his Id.
Something like that:
var form = FormApp.openById('FORM_B_ID');
ScriptApp.newTrigger('onNewFormBSubmit')
.forForm(form)
.onFormSubmit()
.create();

Edit Form Responses as soon as it is submitted

Suppose I have a Google Forms that has only one item: a short answer item. As soon as I submit the form I would like a script so that it changes the response. For example, whatever the user enters to the question, I would like a script to change it to be "foo". The form responses Google Sheet should also show "foo" as the response.
I know it involves something like ScriptApp.newTrigger("edit_response").forForm(form).onFormSubmit().create(); where form = FormApp.getActiveForm() and edit_response is a function that takes the event e. But I can't seem to find a method that can modify form responses...
A Form response inside of a Google Form can NOT be edited with Apps Script. A response saved to a spreadsheet can be changed, but an existing response in a Form can not be changed. A Form response can be deleted with code, but not edited with any Apps Script methods.
You can manually set up an On Form Submit trigger. There is no need to create a trigger from code unless you are doing something like creating new Forms with code, and distributing them automatically. Or having people install an Add-on to the Form.
Form responses are always written into the Form. You can also set a spreadsheet as the response destination. In that case, the Form answers will be saved to both the Form and a spreadsheet. You can not intercept the data before it's written into the Form. But you can change it immediately after it's written.
The function that serves as the On Form Submit trigger can receive a JavaScript object with Form data. The variable name used for the event object is often the letter "e", because the letter "e" is the first character in the word "Event." But the variable name can can be anything.
function myOnFormSubmitFunc(e) {};
An On Form Submit trigger can be either in the Form, the Sheet, or both. The On Form Submit object for the Sheet is different than for the Form. For example, with the Sheet On Form Submit object, you can directly get an array of values.
var arrayOfValues = e.values;
Apps Script Documentation - Sheets Form Submit events
There is a FormResponse class:
Apps Script Documentation - FormResponse
But it can not edit an existing Form response in the Form.

sending automatic email newsletter from google spreadsheet

I would like to be able to send an automatic email message to those who complete a google form . There responses are fed to a google spreadsheet, and I'd like to be able to set it up so that anytime someone completes the form, they are sent the email. Any idea how to do this? I've tried the google tutorial about sending emails from a spreadsheet, but since this is not an automatic function, it does not suit my needs. Any suggestions?
Create an installable trigger in the Form to run for the on Form Submit event. Use a function like getFormDataFields to grab the data from the form submission event. Use the MailApp.sendEmail function to blast out an email. Provide it the necessary parameters.
function myFunction(e) {
var data = getFormDataFields(e); //data['Question Name']
MailApp.sendEmail();
}
function getFormDataFields(e){
var dataFields = [];
for (property in e.namedValues){
dataFields[property] = e.namedValues[property][0];
}
return dataFields;
}