Google apps Script won't record submissions - javascript

Below is a program that I put together, from research and some of my own adding, and I'm having many issues with it. The record_submission function isn't working properly. Every time I test with someone submitting their name, it won't properly record the information which then effects the next function, the notification function which I wrote to automatically send me an email once someone submits a response. Would appreciate some help.
Attached are the images of the Google spreadsheet that I want updated whenever someone submits a response as well as the face of the website people will be submitting information from. The record function is supposed to do that. It's giving me a error saying that the variable isn't properly assigned or something of the sort and the notification email doesn't work properly either.
This is the whole JavaScript code:
//* This function handles the get request from the web browsers */
function doGet(e)
{
//return form.html as the response return
HtmlService.createHtmlOutputFromFile('form.html');
}
// Record all the information entered into the form into a Google Sheet.
function record_submission(form)
{
Logger.log(form);
var ss = SpreadsheetApp.openById("1dQQ1b3NjeYgVEOLIaSNB-XCZwAPAQr6C85Wdqj-sBM8");
var sheet = ss.getSheets()[0]; // Assume first sheet collects responses
// Build a row of data with timestamp + posted response
var row = [ new Date(), // Timestamp
form.last_name[0], // last name
]; // Make sure we are the only people adding rows to the spreadsheet
var lock = LockService.getPublicLock(); // Wait for up to 30 seconds for other processes to finish.
var locked = lock.tryLock(30000);
if (locked)
{
// Save response to spreadsheet
var rowNum = sheet.getLastRow() + 1;
sheet.getRange(rowNum, 1, 1, row.length).setValues([row]);
// Release the lock so that other processes can continue.
lock.releaseLock();
var result = "Response Recorded: \n
"+row.join('\n ');
}
else
{
// Failed to get lock
result =
"System busy, please try again.";
}
// Report result of POST, in plain text
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.TEXT);
}
// Send an email to yourself notifying you when someone made a submission.
function notification(last_name, assignment_name)
{
var subject = "New Submission"; MailApp.sendEmail("*my email*#gmail.com",
subject, 'New submission received from ' + last_name + ' for the
assignment: ' + assignment_name );
}
/* This function will process the form when the submit button is
clicked */
function uploadFiles(form)
{
try
{
notification('test','test'); //Retrieve a reference to the folder in Google Drive
var folder_name = "Test_Folder"
var folder =
DriveApp.getFolderById("0By69oDzO6OluTm9KNGVuaUZZdE0");
// Create a new folder if the folder does not exist
if (!folder)
{
folder = folder.createFolder(folder_name);
}
//Get the file uploaded through the form as a blob
var blob = form.myFile;
var file = folder.createFile(blob);
//Set the file description as the name of the uploader
file.setDescription("Uploaded by " + form.LastName);
//Set the file name as the name of the uploader
file.setName(form.LastName + "_" + form.AssignmentName);
//This function should store the information of the submission to a Google Sheet
record_submission(form);
//This function should notify you when there has been a submission
notification(form.LastName, form.AssignmentName);
// Return the download URL of the file once its on Google Drive
return "File uploaded successfully " + file.getUr1();
}
catch(error)
{
// If there's an error, show the error mesage return
error.toString();
}
}
This is the whole HTML code
File Upload
<!--User inputs -->
<h4>First name</h4>
<input type="text" name="FirstName" placeholder = "Type your first name.." >
<h4> Last Name </h4>
<input type="text" name = "LastName" placeholder="Your last name...">
<h4> Assignment Name </h4>
<input type="text" name="Course" placeholder="Course number">
<!--File upload-->
<h4>Upload</h4>
<input type="file" id="file" name="myFile" style="display:block; margin: 20px;" value = "myFile">
<!-- Submit button -->
<input type="submit" value="Submit"
onclick= "this.value='Uploading..';
google.script.run.withsuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form> <div id="output"> </div> <script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
/*check to see if the user's first name input is empty.
If it is empty alert the user to fill in his/her first name */
</script>
<style>
input {display:block; margin: 20px; }
</style>
</body> </html>

I see that your 'input' tags are not wrapped in a 'form' tag, so what gets passed to the 'onclick' function as parameter might actually be the entire <body> tag. Are your inputs nested inside the <form> tag? If not, then this.parentNode would be the entire body of the HTML document.
I put together the quick example illustrating the entire process. On the client side, we are listening for the form submit event. Once the event fires, we call the server-side function via google.script.run and pass the form object to that function as an argument.
Code.gs
function onOpen(){
var ui = SpreadsheetApp.getUi();
ui.showSidebar(HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('siderbar'));
}
function logFormObject(form){
Logger.log(form); //check the logs by pressing Ctrl + Return
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; // get the 1st sheet in the spreadsheet
sheet.appendRow([form.name, form.lastName, form.age]); //create row contents array from the form object and pass it to the appendRow() method
}
HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm">
Name <br>
<input name="name" /> <br>
Last Name: <br>
<input name="lastName" /> <br>
Age: <br>
<input name="age" /> <br>
<input type="submit" value="send">
</form>
<script>
window.onload = function(){
var form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); //prevents redirect to another page
google.script.run.logFormObject(this); // calling the server function in Code.gs
});
}
</script>
</body>
</html>

Related

Insert Username and Email ID into a list/array and display it using HTML and Javascriot

I'm trying to create a function such that, when the form is submitted the details filled by the user (ie his/her name and email id) is appended to a list/array. And then the list/array is displayed.
For example...
When I fill in the credentials for the first time:
Name - A
Email - something#abc.com
The output on submitting the form should be:
[["A", "something#abc.com"]]
When I fill in the credentials for the second time:
Name - B
Email - someone#xyz.com
The output on submitting the form should be:
[["A", "something#abc.com"], ["B", "someone#xyz.com"]]
But when I tried this, I am not getting the output of the list/array.
Here's what I tried...
const info = [];
function display(){
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
}
<body>
<script src="script.js"></script>
<form onsubmit="return(display())">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>
</body>
The reason it's not displaying the data is for two reasons.
Everytime you submit the form, it refreshes the page. To prevent this you have to prevent the default action of the button submission. Which can be done using the function preventDefault() via an event. Better explained in the code.
You have not appended the created element to anything element, so it is not displaying anywhere on the webpage.
Both can be resolved by checking the code and it's explanation below!
const info = [];
function display(e){ // the `e` parameter is the event passed in.
e.preventDefault(); // We run the function preventDefault to prevent the page from reloading.
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
document.body.appendChild(text); // You haven't appended the information to
// anything, here I append the created Element to the Body so it displays, but do note, that this displays
// the full list, you may want to change this to display only the newer data
// or perhaps append to a element that prints out each time a new user is added.
//console.log(info); You can see that the array now updateds in the console.
}
<script src="script.js"></script>
<!-- Pass the event of submitting a form as an argument -->
<form onsubmit="display(event)">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>

form input reload page with appended url

I have the following form posted on a wordpress page.
I´d like to catch users without referrers to set the referrer on their own (that referrer part is all handled by a plugin... does not matter here).
The registration form Url is like:
http://myurl.com/register/
The code below just works fine. Inserted directly into the wp page editor (text).
Except it creates a Url like follows:
http://myurl.com/register/?id=testinput
How do i get the resulting Url to be formatted this way?:
http://myurl.com/register/sp/testinput
<h3>Your ID</h3>
<p>Please input your ID</p>
<form id = "submit_id_form" onsubmit="myIDFunction()">
<input type="text" name="id">
<input type="submit" value="Confirm">
</form>
<?php
function myIDFunction(){
var action_src = "http://myurl.com/register/" + document.getElementsByName("id")[0].value;
var submit_id_form = document.getElementById('submit_id_form');
submit_id_form.action = action_src ;
} ?>
</script>
This is the original form code (reference below) i`m trying to modify:
<form id = "your_form" onsubmit="yourFunction()">
<input type="text" name="keywords">
<input type="submit" value="Search">
function yourFunction(){
var action_src = "http://localhost/test/" +
document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
</script>
I tried to append the /sp/ part and remove the appended question mark "?" in the code above.. but i´m totally stuck with coding. (I´m a "clicker" not a coder so to speak)
Thank you very much guys and gals :)
Original Code is from here
You have to return true from method called on onsubmit as
function yourFunction(){
var action_src = "http://localhost/test/" + document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
return true;
}

Validating HTML Input fields when uploading file using google HTML Service

I have been tinkering with this problem for most of today and cannot seem to get to a solution with my problem.
I found a script using .gs and html and javascript online which allowed me to upload a file to a google form. At issue though is that I am trying to modify the form to ensure that individuals who upload a file also include their name and email.
I am including my code below.
Essentially, after I call the submit button, I cannot get the code to check the 2 given fields. Can you provide some advice? If I take the 'check' out, the program runs. However, I cannot get the code right to check that the fields are filled out.
Thanks in advance.
/* The script is deployed as a web app and renders the form */
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
// This is important as file upload fail in IFRAME Sandbox mode.
}
/* This function will process the submitted form */
function uploadFiles(form) {
try {
/* Name of the Drive folder where the files should be saved */
var dropbox = form.myName + "Design request form folder" + form.myEmail;
var folder, folders = DriveApp.getFoldersByName(dropbox);
/* Find the folder, create if the folder does not exist */
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
/* Get the file uploaded though the form as a blob */
var blob = form.myFile;
var file = folder.createFile(blob);
/* Set the file description as the name of the uploader */
file.setDescription("Uploaded by " + form.myName);
/* Return the download URL of the file once its on Google Drive */
return "File uploaded successfully " + file.getUrl();
} catch (error) {
/* If there's an error, show the error message */
return error.toString();
}
}
<!-- Include the Google CSS package -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<!-- You can also include your own CSS styles -->
<style>
form { margin: 40px auto; }
input { display:inline-block; margin: 20px; }
</style>
<script>
// The function will be called after the form is submitted
function uploadFile() {
var x=document.coForm.fieldName.value;
if (x == null || x ==""){
alert(x);
return false;}
document.getElementById('uploadFile').value = "Uploading File..";
google.script.run
.withSuccessHandler(fileUploaded)
.uploadFiles(document.getElementById("coForm"));
return false;
}
// This function will be called after the Google Script has executed
function fileUploaded(status) {
document.getElementById('coForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<!-- This is the HTML form -->
<form id="coForm" name="coForm">
<!-- Text input fields -->
<input type="text" class="required" id="fieldName" name="myName" placeholder="Your name..">
<input type="email" class="required" id="fieldEmail" name="myEmail" placeholder="Your email..">
<!-- File input filed -->
<input type="file" name="myFile">
<!-- The submit button. It calls the server side function uploadfiles() on click -->
<input type="submit" id="uploadFile" value="Upload File" onsubmit="uploadFile();">
</form>
<!-- Here the results of the form submission will be displayed -->
<div id="output"></div>
Make the "Submit" button a regular button and change the attribute to onmouseup:
<input type="button" id="uploadFile" value="Upload File" onmouseup="uploadFile();">
Remove class="required" from the input fields:
<!-- Text input fields -->
<input type="text" id="fieldName" name="myName" placeholder="Your name..">
<input type="email" id="fieldEmail" name="myEmail" placeholder="Your email..">
Add this code to your uploadFile() function:
function uploadFile() {
var name = document.getElementById('fieldName').value;
var email = document.getElementById('fieldEmail').value;
console.log('name: ' + name);
console.log('email: ' + email);
if (name === "" || email === "") {
alert("Your name and/or email is missing!");
return;
};
Note the console.log() statements. They print information to the browsers console log. To open the browsers log, hit the f12 key, (for Chrome and some others)

woocommerce POSTing data before javascript (jQuery) finishes

i have a custom gateway (which works perfectly), the problem is when a customer buys something for the first time, there is some token than needs to be generated with the card info, the thing is that just before that token is generated, the form tries to submit, but an error is displayed saying that "the object could not be found", so, no refresh and nothing, if i press again the submit button (or "place order" button) everything works!.
i believe that by that second time, the token is generated and in the corresponding hidden field:
here is my code, hope somebody could help me :S
HTML (from the chrome inspector):
<input type="hidden" name="card-name" data-conekta="card[name]">
<input type="hidden" name="exp-month" data-conekta="card[exp_month]">
<input type="hidden" name="exp-year" data-conekta="card[exp_year]">
<input type="hidden" name="conektaTokenId" value="">
<input type="hidden" name="conektaCustId" value="false">
Javascript
jQuery(window).load(function() {
var form;
var first_name;
var last_name;
var cvc;
jQuery('form[name="checkout"]').submit(function(event) {
jQueryform = jQuery(this);
Conekta.setPublishableKey(jQuery('input[name="pbkey"]').val());
console.log('entro');
if( jQuery('input[name="conektaCustId"]').val()=="true" && jQuery('input[name="conektaTokenId"]').val().substr(0,4)!="tok_"){
console.log('entro');
first_name = jQuery('#billing_first_name').val();
last_name = ' ' + jQuery('#billing_last_name').val();
expiry = jQuery('#conekta_card-card-expiry').val().replace(/ /g, '').split("/");
jQuery('input[name="card-name"]').val( first_name + last_name );
jQuery('input[name="exp-month"]').val( Number(expiry[0]));
jQuery('input[name="exp-year"]').val( Number(expiry[1]));
jQueryform.prepend('<span class="card-errors"></span>');
Conekta.token.create(jQueryform, conektaSuccessResponseHandler, conektaErrorResponseHandler);
woocommerce_order_button_html
return false;
}
else{
return;
}
});
var conektaSuccessResponseHandler= function(response){
var token_id = response.id;
jQuery('input[name="conektaTokenId"]').val(token_id);
}
var conektaErrorResponseHandler= function(response){
jQueryform.find('.card-errors').text(response.message);
}
});
i have found the solution, you have to add the class processing to the checkout form and just when you finished procesing your data to be send to wherever you need to (usually wordpress/woocommerce), remove that class so the form can submit the new data.

How to Get Some Data and set into other page using javascript

I have 3 website pages
1) Where My form Saved
2) Results.html
3) an onther page like results.html
When i enter zip code and press enter its show some data which is fetched from Website, i have one more page like results.html and the code is exactly but data is different, But problem is that when i try to show that an other data it again asking about zip code but user already put it on home page, i need that user can put zip code on home page and the zipcode set on all the pages that i need using javascript.
Any thing like this possible.
See the live example
http://innovativeartz.com/Query
Enter Zip : 95110 its shows the data and than you see on right side HOME button just click here its asking the zip code again i need it will put automaticly since user input it on homepage.
Thanks
**HTML**
<form action="results.html" method="get" >
Zip Code: <input type="text" name="zipcode" size="10" maxlength="5" /><br />
<input type="submit" name="search" value="Get Quotes" />
</form>
**Java Script**
<script type="text/javascript">
function getQueryStringVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];}}}
ni_ad_client = "579660";
ni_res_id = 2;
ni_alt_url = "https://www.shmktpl.com/search.asp";
ni_zc = getQueryStringVariable('zipcode');
ni_str_state_code = getQueryStringVariable('statecode');
ni_var1 = "";
ni_display_width = 650;
ni_display_height = 1000;
ni_color_border = "";
ni_color_bg = "";
ni_color_link = "";
ni_color_url = "";
ni_color_text = "";
</script>
<script type="text/javascript" src="https://www.shmktpl.com/retrieve_listings.asp"></script>
<noscript><img src="https://www.shmktpl.com/images/nojs/image.asp?src=579660&res=2" border="0"></noscript>
The Home button on the right is just a simple a-link. I presume that you should append the zipcode to the end of this link's href, using JavaScript.

Categories

Resources