HTML Form with Google Sheets - SheetDB - Google Sheets REST API

How to submit data to Google Sheets using HTML form

Connecting to the Google API and sending some data to a spreadsheet is quite difficult and time consuming. You need to create an app, manage OAuth tokens, and do a few things between the site and the Google API. With a little help from SheetDB, you can do it in less than a few minutes!

In this article we're gonna use this spreadsheet: https://docs.google.com/spreadsheets/d/1mrsgBk4IAdSs8Ask5H1z3bWYDlPTKplDIU_FzyktrGk/edit

This is a simple HTML form. After submitting one row will be added to the spreadsheet. But remember to put case sensitive column names inside data object like so: data[column name]

<form
  method="post"
  action="https://sheetdb.io/api/v1/58f61be4dda40">
    ID: <input name="data[id]">
    Name: <input name="data[name]">
    Age: <input name="data[age]">
    <button type="submit">Submit</button>
</form>

And this simple HTML code works, without any JavaScript. But in response we get {"created":1}. This is information in json format that we have successfully added one line. For programming, this is perfectly fine, but the end user may be confused. To do this in a more friendly way, we can display a message or redirect the user (e.g. to a "thank you" page).

Alert / redirect or any JS code

We need to add some javascript code to make it work.

<form method="post" id="sheetdb-form"
  action="https://sheetdb.io/api/v1/58f61be4dda40">
    ID: <input name="data[id]">
    Name: <input name="data[name]">
    Age: <input name="data[age]">
    <button type="submit">Submit</button>
</form>

<script>
  var form = document.getElementById('sheetdb-form');
  form.addEventListener("submit", e => {
    e.preventDefault();
    fetch(form.action, {
        method : "POST",
        body: new FormData(document.getElementById("sheetdb-form")),
    }).then(
        response => response.json()
    ).then((html) => {
      // you can put any JS code here
      alert('success')
    });
  });
</script>

You can replace alert() with any JavaScript code. For example if you want to redirect a user, just replace it with this code:

window.location.href = 'https://yourwebsite.com/thank-you';

Have question?

If you have any questions feel free to ask us via chat or .