I wanted to update the entire row with new submitted data based on ID. I have a form on my page that sends the data to my sheet using Javascript.
Here's the simple script that sends based on input ID:
<script>
const scriptURL = "https://script.google.com/macros/s/AKfycxxxxxx/exec";
const form = document.forms['google-sheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => document.getElementById("conf").submit() )
.catch(error => console.error('Error!', error.message))
})
</script>
Here's the app script I got online:
var sheetName = 'Sheet1' var scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1
var newRow = headers.map(function(header) {
return header === 'timestamp' ? new Date() : e.parameter[header]
})
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(e.parameter.callback + "(" + JSON.stringify({ 'result': 'success', 'row': newRow })+ ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
catch (e) {
return ContentService
.createTextOutput(e.parameter.callback + "(" + JSON.stringify({ 'result': 'error', 'error': e })+ ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT)
}
finally {
lock.releaseLock()
}
}
I was able to post the data on my sheet, but I wanted to update the entire row if the ID is found, and insert if ID is not found: