Home > Net >  doGet fails when same commands are called as a subfunction within it
doGet fails when same commands are called as a subfunction within it

Time:09-15

Trying to learn Google Web Apps, I'm having the hardest time in 4 years of studying Google services. At this point, with help from other people, I have assembled a Web App form which successfully processes a few questions and accepts the submission of a file, sending the file to a folder on my Google Drive, appending the form answers to a Google Sheet, and sending me an email alerting me to the form submission. I think I understand how it works, but in trying to make the simplest of changes to it, it stopped working and gave me an error message I don't what to do with.

The form requires the user to upload an image of their COVID vaccination card. Since some people have more than one card, the form allows the user to upload more than file. This screen shot shows what the form displays upon successful submission.

screen snap

The form fields and their answers remain in place, and below them appears the message "Uploaded successfully! You may upload another." What I want to have happen, besides a message like this appearing, is for all form fields and their answers disappear except for the Vacc Card/Choose File and Submit buttons.

So, I am trying to follow the instructions in this video from the highly popular YouTube Channel Learn Google Sheets & Excel Spreadsheets: Create Views (Pages) in Web App - Google Apps Script Web App Tutorial - Part 7

In this video, we see how to make the submission of a Web App form add to the current URL the string "?v=form" or "?v=whatever" and have the DoGet(e) function offer a different HTML file depending on whether the URL contains "&v" and if does, what follows that.

However, in following THE VERY FIRST STEP in the instructions, the App stopped working. All I did was cut what was inside the function doGet(e), place it inside a new function loadForm(), and put inside the doGet a calling of that function:

function doGet(e) {
  if (e.parameters.v == 'form') {
    return loadForm()
  } 

This one change caused the App to fail, returning nothing but a screen reading "The script completed but did not return anything."

My code:

/*

* Original doGet function; works fine. */
// function doGet(e){
//   return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
//   .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
// }

/** Step that caused this to fail: */
function doGet(e) {
  if (e.parameters.v == 'form') {
    return loadForm()
    } // else {HtmlService.createHtmlOutput('<h1>Hello<h1>')} // This would have been the next step, and the step after that making a second HTML file.
    //                                                           Commenting out this step did NOT help.
}

function loadForm(){
  return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
} /** There you have it. All that follows is part of what works. */

function uploadFiles(formObject) {
  var folderID = "1nvhxUoj9uRlE0KpBNjW3cosIuuRpAQly"; // Massage / VaccinationCards 
  try {
    var folder = DriveApp.getFolderById(folderID);
    var fileUrl = "";
    //Upload file if exists 
    if (formObject.myFile.length > 0) {
      var name = formObject.name;
      var namePref = formObject.namePref;
      var pronouns = formObject.pronouns;
      var ready = formObject.ready;
      var email = formObject.email;
      var phone = formObject.phone;
      var callTimes = formObject.callTimes;
      var questions = formObject.questions;
      var blob = formObject.myFile;
      var file = folder.createFile(blob);
      fileUrl = file.getUrl();

    } else {
      fileUrl = null;
  }
  SpreadsheetApp.openById("1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50").getSheetByName("cards")
  .appendRow([name, namePref, pronouns, ready, email, phone, callTimes, questions, fileUrl, new Date()]);
  GmailApp.sendEmail('[email protected]', 'New Vax Card Uploaded!', 'Hey sweetie, smells like business! https://docs.google.com/spreadsheets/d/1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50/edit', {name: 'Vacc Card Robot'});
  return fileUrl;
  } catch (error) {
    return error.message;
  }
}

My HTML:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body style = "background:none transparent;">
  <!-- <link href="/tpm-styles.css" rel="stylesheet" type="text/css"> -->
  <link href="https://transformphillymassage.com/tpm-styles.css" rel="stylesheet" type="text/css">
  <link href="https://transformphillymassage.com/formstyles.css" rel="stylesheet" type="text/css">
    <form id="myForm" onsubmit="handleFormSubmit(this)">
      <p>
        <label for="FormControlFile">Legal Name:</label>
        <input name="name"  type="text" size="35" required/>
      <br>
        <label for="FormControlFile">Preferred Name:</label>
        <input name="namePref"  type="text" size="30">
      <br>  <label for="FormControlFile">Pronouns:</label>
        <input name="pronouns"  type="text" size = "35">
      </p>
      
      <p>
        <label for="FormControlFile">Choose One:</label>
  <!-- <select id = "id_ready" name = "ready"  required/> -->
        <!-- <select id = "id_ready" name = "ready" required/> -->
        <select name = "ready"  required/>
          <option value = "I'm ready to book!">I'm ready to book!</option>
          <option value = "I have questions.">I have questions.</option>
        </select>
      </p>    
      <p>
        <label for="FormControlFile">email:</label>
        <input name="email"  type="text" size = "40" required/>
     <br>
        <label for="FormControlFile">Phone Number:</label>
        <input name="phone"  type="text" size = "28" />
      <br>
        <label for="FormControlFile">Best Times To Call:</label><br>
        <input name="callTimes"  type="text" size="50"/>      
      </p>
      <p>
        <label for="FormControlFile">Vacc Card:</label>
        <input name="myFile"  type="file" required/>     
      </p>
      <p>
        <label for="FormControlFile">Questions / Comments:</label><br>
        <textarea name ="questions"  cols="45" rows="4"></textarea>
      <br>

      <button type="submit"><span >Submit</span></button>
      </p>
  </form>
  <div id="urlOutput"></div>
    <script>
      function preventFormSubmit() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i  ) {
          forms[i].addEventListener('submit', function(event) {
            event.preventDefault();
          });
        }
      }

      window.addEventListener('load', preventFormSubmit);

      function handleFormSubmit(formObject){
        google.script.run.withSuccessHandler(updateUrl).withFailureHandler(onFailure).uploadFiles(formObject); 
      }

      function updateUrl(url) {
        var div = document.getElementById('urlOutput');
        if(isValidURL(url)){
          div.innerHTML = '<div  role="alert"><a href="'   url   '">Uploaded successfully!</a><br>You may upload another.</div>';
          // document.getElementById("myForm").reset();
        } else {
        //Show warning message if file is not uploaded or provided
          div.innerHTML = '<div  role="alert">'  url  '!</div>';
        }
      }

      function onFailure(error) {
      var div = document.getElementById('urlOutput');
      div.innerHTML = '<div  role="alert">'  error.message  '!</div>';
      }

      function isValidURL(string) {
      var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\ .~#?&//=]*)/g);
      return (res !== null);
      }
    </script>
  </body>
</html>

CodePudding user response:

return is missing on the else part of your if-else statement

Replace your doGet function by

function doGet(e) {
  if (e.parameters.v == 'form') {
    return loadForm()
  } else {
    return HtmlService.createHtmlOutput('<h1>Hello<h1>')
  }
}
  • Related