Reputation: 115
How can I return something from code.gs to index.html.
I have tried this in "Index.html", but this doesn't work.
index.html
$('#test').click(function() {
alert(google.script.run.getAmountOfImages());
});
Code.gs
function getAmountOfImages()
{
return "Tom"
}
Please help.
Upvotes: 2
Views: 3598
Reputation: 2486
google.script.run is what you need.
See the example below.
code.gs
function runOnGsAndGetValue() {
return "Hello World!";
}
function runOnGsOnly() {
Logger.log("Hello World"); // On Appscript go to 'View' -> 'Logs' to see your Logs
}
sample.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="para">Hello World</p>
<br>
<button onclick="onlyRun()">Run Code in Code.gs Only</button>
<br><br>
<button onclick="runAndGet()">Run Code in Code.gs and Return a Value</button>
<script>
function setText(text){
var div = document.getElementById('para');
div.innerHTML = text;
}
function onSuccess(str) {
setText(str);
}
function onFailure(error) {
setText("ERROR: " + error.message);
}
function runAndGet(){
google.script.run.withFailureHandler(onFailure).withSuccessHandler(onSuccess).runOnGsAndGetValue();
}
function onlyRun(){
google.script.run.runOnGsOnly();
}
</script>
</body>
</html>
Upvotes: 1
Reputation: 2717
According to the documentation
"google.script.run is an asynchronous client-side JavaScript API available in HTML-service pages that can call server-side Apps Script functions."
therefore your result will be returned in a callback. So you will have to use Handler functions i.e withFailureHandler
and withSuccessHandler
google.script.run
.withFailureHandler(function(err){
console.error("error occured", e);
})
.withSuccessHandler(function(res){
alert(res);
})
.getAmountOfImages();
res
Parameter in success handler callback function will hold the response from google app script.
Upvotes: 4