Demo: Send Data to Google Sheet With Google Apps Script (2020)

The Google Sheet
[url=https://docs.google.com/spreadsheets/d/1DAdjgwff-zBlbntUQzzWONzmeXn4isotC7eUjpUXY8k/edit?usp=sharing][color=#0000ff][/color][/url][color=#0000ff][url=https://docs.google.com/spreadsheets/d/10Uuv9IFJiAjcW_jBAA5--srfsUuibgTwaFIW6kgXYD4/edit#gid=0]https://docs.google.com/spreadsheets/d/10Uuv9IFJiAjcW_jBAA5--srfsUuibgTwaFIW6kgXYD4/edit#gid=0[/url][/color]
Step by Step Tutorial for Setting up the Google Sheets, Google Apps Script and Geogebra's JavaScript
[size=100][size=150]The steps below roughly follow[br][url=http://railsrescue.com/blog/2015-05-28-step-by-step-setup-to-send-form-data-to-google-sheets/]http://railsrescue.com/blog/2015-05-28-step-by-step-setup-to-send-form-data-to-google-sheets/[br][/url][br][b]1. Setup the Google Sheets[/b][br][br](a) Go to https://drive.google.com, click "NEW" and choose "Google Sheets".[br][br](b) Put the following in the first 7 cells in the first row. You can change the names and the number of items later. These names need to be matched in the JavaScript of the Geogebra file in Step 3. The first cell is used for recording the timestamp.[br][br][table][tr][td][color=#999999]Timestamp[/color][/td][td][color=#999999]id[br][/color][/td][td][color=#999999]Class[/color][/td][td][color=#999999]Class Number[/color][/td][td][color=#999999]x-coord[/color][/td][td][color=#999999]y-coord[/color][/td][td][color=#999999][/color][/td][/tr][/table][/size][/size]
[size=100][size=150][b]2. Setup the Google Apps Script[/b][br](a) Click "Tools" and choose "Script editor...".[br][br](b) Replace the existing script with the following (which is modified from https://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/):[br][code][/code][br][br][size=85][code]// 1. Enter sheet name where data is to be written below[br] var SHEET_NAME = "Sheet1";[br][br]// 2. Run > setup[br]//[br]// 3. Publish > Deploy as web app[br]// - enter Project Version name and click 'Save New Version'[br]// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)[br]//[br]// 4. Copy the 'Current web app URL' and post this in your form/script action[br]//[br]// 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)[br][br]var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service[br][br]// If you don't want to expose either GET or POST methods you can comment out the appropriate function[br]function doGet(e){[br] return handleResponse(e);[br]}[br][br]function doPost(e){[br] return handleResponse(e);[br]}[br][br]function handleResponse(e) {[br] // Google announced the LockService[1][br] // this prevents concurrent access overwritting data[br] // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html[br] // we want a public lock, one that locks for all invocations[br] var lock = LockService.getPublicLock();[br] lock.waitLock(30000); // wait 30 seconds before conceding defeat.[br][br] try {[br] // next set where we write the data - you could write to multiple/alternate destinations[br] var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));[br] var sheet = doc.getSheetByName(SHEET_NAME);[br][br] // we'll assume header is in row 1 but you can override with header_row in GET/POST data[br] var headRow = e.parameter.header_row || 1;[br] var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];[br] var nextRow = sheet.getLastRow()+1; // get next row[br] var row = [];[br] var output = "";[br] // loop through the header columns[br] for (i in headers){[br] if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column[br] row.push(new Date());[br] } else { // else use header name to get data[br] row.push(e.parameter[headers[i]]);[br] }[br] }[br] // more efficient to set values as [][] array than individually[br] sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);[br] output = JSON.stringify({"result":"success", "row": nextRow});[br] if (e && e.parameter && e.parameter.callback){[br] // return jsonp success results[br] return ContentService[br] .createTextOutput(e.parameter.callback+"("+ output + ");")[br] .setMimeType(ContentService.MimeType.JAVASCRIPT);[br] }[br] else{[br] // return jsonp success results[br] return ContentService[br] .createTextOutput(output)[br] .setMimeType(ContentService.MimeType.JSON);[br] }[br] } catch(e){[br] output = JSON.stringify({"result":"error", "error": e});[br] if (e.parameter.callback){[br] // if error return this, again, in jsonp[br] return ContentService[br] .createTextOutput(e.parameter.callback+"("+ output + ");")[br] .setMimeType(ContentService.MimeType.JAVASCRIPT);[br] }[br] else{[br] return ContentService[br] .createTextOutput(output)[br] .setMimeType(ContentService.MimeType.JSON);[br] }[br] } finally { //release lock[br] lock.releaseLock();[br] }[br]}[br][br]function setup() {[br] var doc = SpreadsheetApp.getActiveSpreadsheet();[br] SCRIPT_PROP.setProperty("key", doc.getId());[br]}[br][br][/code][/size][br][br][br] [br](c) Then, click the "Save" icon, or click "File", then choose "Save".[br][br](d) Click "Run", then choose "setup". [br][br](e) A dialog of "Authorization required" pops up. Click "Review Permissions". Click "Allow" in the next dialog.[br][br](f) Click "Publish", then choose "Deploy as web app...".[br][br](g) In the popup, choose "New" in "Project version:", then type something about this version in the text box below it. For "Execute the app as:", choose "Me". For "Who has access to the app:", choose "Anyone, even anonymous". Then Click "deploy".[br][br](h) Copy the "Current web app URL", e.g. like https://script.google.com/macros/s/SOME_LONG_KEY_HERE/exec[br][br](i) You can test your script by copy and paste the URL, plus the following without the quotes[br]"?Name=test&Class=1A&Class%20Number=18&x-coord=1&y-coord=2&id=app_001"[br]e.g. like[br][size=85]https://script.google.com/macros/s/SOME_LONG_KEY_HERE/exec?Name=test&Class=1A&Class%20Number=18&x-coord=1&y-coord=2&id=app_001[br][/size][/size][/size][br]This basically sends a GET request with "Name" = test, Class = 1A, Class Number = 18, x-coord = 1, y-coord=2 and id = app_001. The webpage will show something like "{"result":"success","row":14}", which means the data is successfully added to row 14 of the Google Sheet and you then check the Sheet for this new row.
[b]3. Create a geogebra app to send data to the Google Sheet[/b][br](a) You can download the above geogebra file or create a new one. Assume that you have a geogebra file and you want to submit the x, y coordinates of a point, as well as the class and class number of a student. Let's assume that these are stored in variables ax, ay, class and classNum.[br][br](b) Create a new button. Right click it and choose "Object Properties...". Choose "Scripting", then choose "On Click". Then paste the following:[br][br][size=85][code]var class0 = ggbApplet.getValueString("class"); // cannot name a variable as 'class'[br]var classNum = ggbApplet.getValueString("classNum");[br]var ax = ggbApplet.getValue("ax");[br]var ay = ggbApplet.getValue("ay");[br][br]if (confirm("Confirm to submit?\nClass: " + class0 + ", class num: " [br] + classNum + ", point A = ("+ax+", "+ay+")" )) {[br] sendData(class0, classNum, ax, ay);[br]}[br][br][br][br][/code][/size](c) Choose "JavaScript" instead of "Geogebra Script". Then click "OK".[br][br](d) Choose "Global JavaScript". Then paste the following code. (Note that in lines 7 to 11, the names in quotes, i.e. "id", "Class", "ClassNumber", "x-coord" and "y-coord" must exactly match (case sensitive) the names in the header row of the Google Sheet, otherwise, those non-matching cells will contain "undefined" as their value.[br][br][size=85][code]function get(url) {[br] var xhttp = new XMLHttpRequest();[br][br] xhttp.onreadystatechange = function() {[br] if (this.readyState == 4 && this.status == 200) {[br] var response = xhttp.responseText;[br][br] if (response) {[br] response = JSON.parse(response);[br] if (response.result == "success") {[br] console.log("added to row " + response.row);[br] alert("Successfully submitted");[br] } else {[br] alert("Error: " + response.result);[br] }[br][br] }[br] }[br] };[br][br][br] xhttp.open("GET", url, true);[br] xhttp.send();[br][br][br][br]}[br][br]function sendData(class0, num, x, y) {[br] var scriptURL = "https://script.google.com/macros/s/AKfycbw0iQbrj2KFJn67y_L0LHm_dct7HykgI-BqpHyFqgRYy5jcdYUd/exec";[br] var app_name = "shortest distance";[br] if (num !== "") {[br][br] // eg https://script.google.com/macros/s/AKfycbw0iQbrj2KFJn67y_L0LHm_dct7HykgI-BqpHyFqgRYy5jcdYUd/exec?Name=test&Class=1A&Class%20Number=18&x-coord=1&y-coord=2&id=app_001[br][br] // the name "id", "Class", "x-coord", "y-coord" must match the header row in the spreadsheet[br] var url = scriptURL + "?Name=test";[br] url += "&Class=" + class0;[br] url += "&Class%20Number=" + num;[br] url += "&x-coord=" + x;[br] url += "&y-coord=" + y;[br] url += "&id=" + app_name;[br][br] get(url);[br][br] } else {[br] alert("Please input the class and class number");[br] }[br]}[br][br][br][/code][/size][br][br](e) In the [b][i]second line of the code[/i][/b], replace the URL in quotes with the URL obtained in step 2(h).[br][br](f) Click "OK". Then close it.[br][br](g) Click "File", then choose "Export", and choose "Dynamic Worksheet as Webpage", then following the instruction to upload to Geogebratube. Now you can try the geogebra worksheet.[br][br]
References
[1] The Original Tutorial for setting up Google Script for the Spreadsheet[br]https://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/[br][br][2] A step-by-step tutorial based on the above one[br]http://railsrescue.com/blog/2015-05-28-step-by-step-setup-to-send-form-data-to-google-sheets/[br][br][3] Another way to send data to Google Sheet/Google Form by Mr. Alex Chik[br]https://www.geogebra.org/m/eMBf6HAu[br][br][4] Using jonsp to get the response[br]https://developers.google.com/apps-script/guides/content#serving_jsonp_in_web_pages[br]

Informaţie: Demo: Send Data to Google Sheet With Google Apps Script (2020)