I wrote a GAS code to check if the employee is In or Not in (extracting data from Google sheets). The console log give me the right answer but When I click on the button the answer doesn’t appear at the front end. Can you help me to troubleshoot on where I went wrong?
JavaScript
x
32
32
1
<div>
2
<script>
3
function onStatus(notify) {
4
5
var employee = "John Peter";
6
7
var ss = SpreadsheetApp.getActiveSpreadsheet();
8
var mainSheet = ss.getSheetByName("MAIN");
9
var data = mainSheet.getDataRange().getValues();
10
11
12
for (var j = 0; j < data.length; j++){
13
var row = data[j];
14
var mainSheet2 = row[4];
15
var mainSheet3 = row[0];
16
var status = (mainSheet2 =="IN" && mainSheet3 == employee) ;
17
if (status == true){
18
var notify = employee +" You Are In"
19
20
return notify;
21
22
}
23
}
24
document.getElementById('status').innerHTML= notify;
25
}
26
27
</script>
28
<button onclick="onStatus()">Check Status</button>
29
30
<font color='Green' id="status" ></font>
31
</div>
32
Advertisement
Answer
Google provides a very good Client-to-Server Communication guide that I highly suggest you read to get a better understanding of how this works.
You cannot put apps script code (e.g. SpreadsheetApp.getActiveSpreadsheet()
) in your frontend scripts. That code has to be run by the apps script server in the backend and you’ll then call it using a google.script.run
call.
Code.gs
JavaScript
1
21
21
1
function doGet(e) {
2
return HtmlService.createHtmlOutputFromFile('Index');
3
}
4
5
function checkStatus() {
6
var employee = "John Peter";
7
var ss = SpreadsheetApp.getActiveSpreadsheet();
8
var mainSheet = ss.getSheetByName("MAIN");
9
var data = mainSheet.getDataRange().getValues();
10
11
for (var j = 0; j < data.length; j++){
12
var row = data[j];
13
var mainSheet2 = row[4];
14
var mainSheet3 = row[0];
15
var status = (mainSheet2 =="IN" && mainSheet3 == employee) ;
16
if (status == true){
17
return employee + " You Are In";
18
}
19
}
20
}
21
Index.html
JavaScript
1
25
25
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<base target="_top">
5
</head>
6
<body>
7
<div>
8
<button onclick="onStatus()">Check Status</button>
9
<font color='Green' id="status" ></font>
10
</div>
11
12
<script>
13
function onStatus() {
14
google.script.run
15
.withSuccessHandler(updateStatus) // Send the backend result to updateStatus()
16
.checkStatus(); // Call the backend function
17
}
18
19
function updateStatus(notify) {
20
document.getElementById('status').innerHTML= notify;
21
}
22
</script>
23
</body>
24
</html>
25