Skip to content Skip to sidebar Skip to footer

How To Return Specific Data From A Google Apps Script Into Html Web Page

Code.gs function doPost(e) { var id = 'SHEET_ID'; var sheetname = 'verify'; var data = SpreadsheetApp.openById(id).getSheetByName(sheetname).getRange('A1:X100').getValues();

Solution 1:

For what I could understand you want to pass some values to your server side (your Apps Script code) when you submit a form (Preventing the default submitting form behavior). If that's correct, then use the following code in your HTML file.

html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <form id="gform">
      <input  id="subject" />
      <input  id="name" />
      <input type="text" id="searchtext"/>
      <button>Submit form</button>
    </form>
  <script>
    // Callback that runs when the valuesSubmitted function returned some values 
    function onSuccess(val){
      console.log(val);
    }
    
    // Callback that runs when the form is submitted
    function logSubmit(e){
      // Get values from the inputs 
      var submittedVals = {
        "subject": document.getElementById('subject').value,
        "name": document.getElementById('name').value,
        "searchtext": document.getElementById('searchtext').value
      }
      
      // Pass data to the server side 
      google.script.run.withSuccessHandler(onSuccess).valuesSubmitted(submittedVals);
      e.preventDefault();
    }
    
    // Event listener for when the form is submitted
    document.getElementById('gform').addEventListener('submit', logSubmit);
  </script>
  </body>
</html>

The key concept in the JavaScript code is the Class google.script.run, which is a powerful tool that allows you to call your Apps Script functions in the server-side. Using withSuccessHandler(function) you will be able to wait for an Apps Script function to return a value to run later a callback function with the gotten values.

Notice: I also used .preventDefault() to cancel the form's submit behavior.

Now, in your Apps Script code, you will have defined the function that can get the spreadsheet's values in order to pass them to your client-side:

Apps Script

function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');
}

// Called using google.script.run
function valuesSubmitted(val){
  // Values that came from the client side  
  Logger.log(val);
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = ss.getSheets()[0];
  var data = sheet.getRange("Any range you want").getValues();
  // Pass data to the client side
  return data;
}

I didn't do it exactly as in your code, Take my post as guidance and modify it in the parts of the code we have different if you want to.


Post a Comment for "How To Return Specific Data From A Google Apps Script Into Html Web Page"