How To Return Specific Data From A Google Apps Script Into Html Web Page
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><basetarget="_top"></head><body><formid="gform"><inputid="subject" /><inputid="name" /><inputtype="text"id="searchtext"/><button>Submit form</button></form><script>// Callback that runs when the valuesSubmitted function returned some values functiononSuccess(val){
console.log(val);
}
// Callback that runs when the form is submittedfunctionlogSubmit(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 submitteddocument.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];
vardata = sheet.getRange("Any range you want").getValues();
// Pass data to the client sidereturndata;
}
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"