Home > database >  Google Apps Script - Returning Undefined
Google Apps Script - Returning Undefined

Time:07-11

What I want to do:

  1. Submit the values from two textboxes (Last Name & First Name)
  2. Process the two values in Code.gs (Create a string in "Hello LastName, FirstName" format)
  3. Return back the processed value and display it to the third textbox.

Please note that I can do it if the processing of data is in html, but I want to practice doing it in Code.gs since I want to fiddle with Google Sheets in the future, I just wanted to study it little by little. But when I transferred the processing inside Code.gs, the returned data is "undefined". Your help is very much appreciated. Thank you very much!

Present code:

Code.gs:

function doGet(e) {
  return HtmlService
    .createTemplateFromFile('Index').evaluate();
}

function getData(a,b){
  var lastName = a;
  var firstName = b;
  var txtResult = "Hello "   lastName   ", "   firstName;
  return txtResult;
}

Index.html:

<!DOCTYPE html>
<html>
  <body>
    <div>
      <label>Enter Last Name</label>
      <input type="text" id="txtLastName"/></br>
      <label>Enter First Name</label>
      <input type="text" id="txtFirstName"/></br>
      <button id="btnProcess">Process</button></br>
      <input type="text" id="txtResult"/>
    </div>
  </body>

  <script>
    document.getElementById("btnProcess").addEventListener("click", processData);                
    function processData() {
      var lastName = document.getElementById("txtLastName").value
      var firstName = document.getElementById("txtFirstName").value
      document.getElementById("txtResult").value = google.script.run.getData(lastName,firstName);
    }
  </script>
    
</html>

CodePudding user response:

You are missing the withSuccessHandler and withFailureHandler (optional).

<script>
  document.getElementById("btnProcess").addEventListener("click", processData);                
  function processData() {
    var lastName = document.getElementById("txtLastName").value
    var firstName = document.getElementById("txtFirstName").value
    google.script.run.withFailureHandler(errorFunction).withSuccessHandler(successFunction).getData(lastName,firstName);
  }

  function errorFunction(errorMsg) {
    console.log("Something went wrong");
  }

  function successFunction(txtResult) {
    document.getElementById("txtResult").value = txtResult;
  }
</script>
  • Related