Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanMCarter/abc5c211f0a85811e510422e03823452 to your computer and use it in GitHub Desktop.
Save JonathanMCarter/abc5c211f0a85811e510422e03823452 to your computer and use it in GitHub Desktop.
A custom google sheet script, using some exsisting code to get an understanding of how to return data via JSON. This version was made for a client and won't work out of the box for anyone else.
// 1. Enter sheet name where data is to be written below
var SHEET_NAME = "DATA";
// 2. Run > setup
//
// 3. Publish > Deploy as web app
// - enter Project Version name and click 'Save New Version'
// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
// 4. Copy the 'Current web app URL' and post this in your form/script action
//
// 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// Calls the Custom Get Function & returns its return value
function doGet(e)
{
return GetValues();
}
function doPost(e)
{
return handleResponse(e);
}
// Jonathan Carter - March 2020
// Gets the values in Column 2, Row 1 and returns them in a JSON string to be used in engine
function GetValues()
{
// Needed to get data
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// Array that holds all the words you wish to get
var Array = sheet.getRange(2, 1, FindRows(), 1).getValues();
// Randomises the results and limits them to 10
Array = ChooseRandom(Array);
return ContentService
//.createTextOutput(JSON.stringify({"Word 1 - ":sheet.getRange(9, 2, 1, 1).getValue()}))
.createTextOutput(JSON.stringify(Array))
.setMimeType(ContentService.MimeType.JSON);
}
// A little function that gets the number of rows inn the sheet
// https://www.portent.com/blog/analytics/google-app-script-1.htm
function FindRows()
{
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
range = sheet.getLastRow();
return range;
}
// Jonathan Carter - March 2020
// Gets the defined number of array values and returns them
function ChooseRandom(Input)
{
var RtnArray = [];
var MaxNumber = FindRows();
var NumberofWords = 10;
for (var i = 0; i < NumberofWords; i++)
{
var Value = Input[GetRandomIntValue(MaxNumber - 1)];
while (RtnArray.indexOf(Value) != -1)
{
Value = Input[GetRandomIntValue(MaxNumber - 1)];
}
RtnArray.push(Value);
}
return RtnArray;
}
// Jonathan Carter - March 2020
// gets a random int value between 1 & the max number of rows
function GetRandomIntValue(Max)
{
var Number = Math.floor(Math.random() * Max)
return Number;
}
function handleResponse(e)
{
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try
{
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
//var headRow = e.parameter.header_row || 1; Hawksey's code parsed parameter data
var postData = e.postData.contents; //my code uses postData instead
var data = JSON.parse(postData); //parse the postData from JSON
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers)
{
if (headers[i] == "Timestamp")
{ // special case if you include a 'Timestamp' column
row.push(new Date());
}
else
{ // else use header name to get data
row.push(data[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({ "GetValue" : sheet.getRange(1, 1, 1, 1).getValue()}))
.setMimeType(ContentService.MimeType.JSON);
}
catch(e)
{
// if error return this (not sure if its returning an error or what I ask it too)
return ContentService
.createTextOutput(JSON.stringify({"resuggglt":"It Broken, this error", "errgggor": sheet.getRange(1, 1, 1, 1).getValue()}))
//.createTextOutput(JSON.stringify({"resuggglt":"It Broken, this error", "errgggor": e}))
.setMimeType(ContentService.MimeType.JSON);
}
finally
{ //release lock
lock.releaseLock();
}
}
function setup()
{
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
@JonathanMCarter
Copy link
Author

Twine Engine Code for showing the data....

Loading ...

<script src="jquery-3.3.1.min.js"></script> <script> // Scripting to get values - this is in JavaScript // Calls the Google Sheet with the 'GET' method instead of 'POST', note less values are passed in $.ajax({ url:"https://script.google.com/macros/s/AKfycbypqjLgC5tAmJPez9ad4hXwDsBWmfQQYr76GKAGzDKqCi9UBAfk/exec", method: "GET", dataType: "json", }).done(function(data) { // Initilise Variables var DataArray, DisplayArray; // Sets the DataArray to what was returned from the google sheet DataArray = data; // Sets the default value of the DisplayArray to nothing... DisplayArray = ""; // For Each element in the DataArray, add a
(a break/new line) to the string for (i in DataArray) { DisplayArray += DataArray[i] + "
"; } // Sends the final DisplayArray to the HTML code that is above this script document.getElementById("TestElement").innerHTML = DisplayArray; }); </script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment