Search code examples
google-apps-scriptgoogle-sheetsweb-applicationstracking

I'm forced to fill up form twice to execute 2 functions. Suggestions to execute 2 functions in 1 click?


ABOUT: I made a web app for tracking packages for our freight company. Database is on Google Sheets, with two sheets named "Tracker" and "Program" to automatically track packages.

PROCESS:

  1. On the web app I enter the Tracking Number
  2. On click, this gets sent to the Tracker sheet
  3. Program sheet gets the tracking number from Tracker sheet, and takes 2-3 seconds to get data
  4. The data from Program sheet (which only has 1 row of data - only the relevant data) gets sent back to the web app for the client to view

MY PROBLEM: I have to submit the form twice to successfully execute Step 4 above. I tried putting two functions (Step 2 & Step 4) into one button click, but clicking it one time only will say that the tracking number is not found. Is there a function to automatically fill up the form and click the button again (submit twice) after Step 3 of my process? Or any suggestions?


WHAT I'VE TRIED: All these didn't work (they all returned blank). I've placed all of them in between the two functions of Step 2 & 4

  • SpreadsheetApp.flush();
  • Utilities.sleep(3000)
  • LockService.getScriptLock(); lock.waitLock();

RELEVANT CODES & LINKS:

Google Script | Google Sheet

SAMPLE TRACKING NUMBERS: 11424 & 11426 (So you can try changing it in the web app to see what my problem is. Please make sure to open both links above to see changes and to submit the form on the web app twice)

// Process STEP 2
function sendTracking(formObject) {
  google.script.run.processForm(formObject);
  document.getElementById("myForm");
}

// Process STEP 4
function trackingInfo(formObject) {
  google.script.run.withSuccessHandler(createTable).processReturnForm(formObject);
  document.getElementById("myForm").reset();
}
    
// COMBINED: Process STEP 2 & 4
function handleFormSubmit(formObject) {
  sendTracking(formObject); // THIS IS STEP 2
  // IN BETWEEN HERE is where I put the codes I listed above that did not work
  trackingInfo(formObject); // THIS IS STEP 4
}

Solution

  • google.script.run is an asynchronous client-side JavaScript API

    The sequence of sendTracking (STEP 2) and handleFormSubmit (STEP 4) is not gauranteed.

    function handleFormSubmit(formObject) {
      sendTracking(formObject);
    
      function sendTracking(formObject) {
        google.script.run.withSuccessHandler(trackingInfo).processForm(formObject);
      }
    
      function trackingInfo(formObject) {
        google.script.run.withSuccessHandler(createTable).processReturnForm(formObject);
      }
    
      function createTable(formObject) {
        /* ... */
        document.getElementById("myForm").reset();
      }
    }
    

    Reference:

    withSuccessHandler(function)