I am trying to implement a basic CMS via GoogleSheets, so I can edit text directly on the webpage and the edits are sent to the corresponding cell in GoogleSheets… and the webpage gets data from the GoogleSheet, completing the loop.
In principle this seems to work, but instead of overwriting the text in a corresponding cell, the text is appended, creating a new row. However if I edit the cell within the GoogleSheet and refresh my webpage, the input text field values are populated in the correct order.
So here is what I have so far… Fetching data (thanks @MaxZieb)
var xmlhttp = new XMLHttpRequest();
var url = "https://spreadsheets.google.com/feeds/list/XXXXXXXXXXX/od6/public/values?alt=json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
hypeDocument.customData = data;
hypeDocument.showNextScene();
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
adding the data to the value of the text input fields
var data = hypeDocument.customData;
for (i = 0; i < data.feed.entry.length; i++) {
var Input = document.getElementsByClassName('input')[i];
var Title = data.feed.entry[i].gsx$title.$t
Input.value = Title;
}
So far so good, works as expected… Now I can send the values I type into the input fields
var PlaceHolders = document.getElementsByClassName('PlaceHolder');
for (i = 0; i < PlaceHolders.length; i++) {
Input = document.getElementsByClassName('input')[i];
var xmlhttp = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/xxxxxxxxxxxxxxx/exec";
xmlhttp.open("GET", url+"?title="+Input.value , true);
xmlhttp.send();
}
The result is sent and is appended to the sheet but the order seems random, not sequential. Also I need to overwrite the values. I’m using this google script, but can’t work it out. Any pointers would be amazing. Thank you.
// 1. Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
// 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
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
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.
/* // If you are passing JSON in the body of the request uncomment this block
var jsonString = e.postData.getDataAsString();
e.parameter = JSON.parse(jsonString);
*/
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;
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(e.parameter[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({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}