Search for the Article

Save HTML Form Data to Google Sheets using JavaScript

STEP 1:

  1. Create a new sheet.
  2. Name excel file name.
  3. Change the sheet name, if you want ( it is optional).
  4. Run the Script
  5. Replace the exsiting function and Copy and paste above given code in editor
  6. Excecute the function and Deploy it as a Web app publicliy
  7. Google will promote you to access their party app. alllow it to access.
  8. You will get a your automation script URL, save it for now.
	

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(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}
  
  
  

STEP 2:

  1. Name the sheet values as they were mentioned in sheet
  2. Replace the Script URL with your generated Script URL
  3. Add extra element in each form entries name="".
  4. Similary give the form a name=""
  5. Replace the document.form name with the name you provided above, save it.
  6. Save it
	
<script>
  const scriptURL = '<SCRIPT URL>'
  const form = document.forms['submit-to-google-sheet']

  form.addEventListener('submit', e => {
    e.preventDefault()
    fetch(scriptURL, { method: 'POST', body: new FormData(form)})
      .then(response => console.log('Success!', response))
      .catch(error => console.error('Error!', error.message))
  })
</script>