1 Answer

0 votes
by (487 points)

How to submit a simple HTML form to a Google Sheet using only HTML and JavaScript.

This example shows how to set up a mailing list form that sends data to Google Sheets.

1. Set up a Google Sheet

Go to Google Sheets and create a new sheet. This is where we'll store the form data.

* Set the following headers in the first row:

       A             B           C           D            E

Timestamp  name  email  phone  message

* Rename the form "Form Google Sheets"

2. Create a Google App Script

Click on Extensions -> Apps Script. This will open new Google Script. Rename it to something like "Form Script".

Now Replace the myFunction() {

section code with the following code snippet:

var SHEET_NAME = "Sheet1";

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

function doGet(e){

  return handleResponse(e);

}

function doPost(e){

  return handleResponse(e);

}

function handleResponse(e) {

  var lock = LockService.getPublicLock();

  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

  try {

    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));

    var sheet = doc.getSheetByName(SHEET_NAME);

    var headRow = e.parameter.header_row || 1;

    var headers = sheet.getRange(111sheet.getLastColumn()).getValues()[0];

    var nextRow = sheet.getLastRow()+1// get next row

    var row = [];

    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]]);

      }

    }

    sheet.getRange(nextRow11row.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());

}

And Save the project before moving on to the next step.

3. Run the initialSetup function

You should see a modal asking for permissions. Click Review permissions and continue to the next screen. Because this script has not been reviewed by Google, it will generate a warning before you can continue. You must click the "Go to Mailing List (Unsafe)" for the script to have the correct permissions to update your form.

After giving the script the correct permissions, you should see the following output in the script editor console:

Now your script has the correct permissions to continue to the next step.

4. Add a trigger for the script

Select the project "Triggers" from the sidebar and then click the Add Trigger button.

In the window that appears, select the following options:

Choose which function to run: doPost

Choose which deployment should run: Head

Select event source: From spreadsheet

Select event type: On form submit

Then select "Save".

5. Publish the project

Now your project is ready to publish. Select the Deploy button and New Deployment from the drop-down.

Click the "Select type" icon and select Web app.

In the form that appears, select the following options:

Description: Mailing List Form (This can be anything that you want. Just make it descriptive.)

Web app → Execute As: Me

Web app → Who has access: Anyone

Then click Deploy.

Important: Copy and save the web app URL before moving on to the next step.

6. Configure your HTML form

Create a HTML form named "index.html" and paste the following code. 

And replacing YOUR_WEBAPP_URL with the URL you saved from the previous step then save the file.

Now when you submit this form from any location, the data will be saved in the Google Sheet.

by (487 points)

Code for index.html for the contact web page...........

<!DOCTYPE html>

<html lang='en'>

  <head>

    <meta charset='utf-8'>

    <meta content='IE=edge' http-equiv='X-UA-Compatible'>

    <meta content='width=device-width, initial-scale=1' name='viewport'>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<style>

a{ color:#2D3E52

} label {

display:block;

margin-top:20px;

}

textarea {

width:50%;

height:150px;

background:#efefef;

border:1px solid #dedede;

padding:10px;

margin-top:3px;

font-size:0.9em;

color:#3a3a3a;

-moz-border-radius:5px;

-webkit-border-radius:5px;

border-radius:5px;

}

input,select{

width:50%;

height:25px;

background:#efefef;

border:1px solid #dedede;

padding:10px;

margin-top:3px;

font-size:0.9em;

color:#3a3a3a;

-moz-border-radius:5px;

-webkit-border-radius:5px;

border-radius:5px;

}

input:focus, textarea:focus {

border:1px solid #97d6eb;

}

button {

width:50%;

height:38px;

border:none;

margin-top:20px;

cursor:pointer;

color:white;

background:#335599;

}

button:hover {

opacity:.9;

}

</style>

  </head>

  <body><center>

    <form id='foo'>

      <p>

        <label>Your Name:</label>

        <input id='name' name='name' type='text' required>

      </p><p>

        <label>Email Address:</label>

        <input id='email' name='email' type='email' required>

      </p><p>

        <label>Phone Number:</label>

        <input id='phone' name='phone' type='tel' required>

      </p><p>

        <label>Message:</label>

        <textarea id='message' name='message' rows='5' required></textarea>

      </p>

        <div id='success'></div>

        <button type='submit'onClick="window.location.reload();">Send</button>

    </form>

</center>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

  <!-- Custom Theme JavaScript -->

  

<script>

var request;

$("#foo").submit(function(event){

    if (request) {

        request.abort();

    }

    var $form = $(this);

    var $inputs = $form.find("input, select, button, textarea");

    var serializedData = $form.serialize();

    $inputs.prop("disabled", true);

    request = $.ajax({

        url: "YOUR_WEBAPP_URL",

        type: "post",

        data: serializedData

    });

    request.done(function (response, textStatus, jqXHR){

        console.log("Hooray, it worked!");

        console.log(response);

        console.log(textStatus);

        console.log(jqXHR);

    });

    request.fail(function (jqXHR, textStatus, errorThrown){

        console.error(

            "The following error occurred: "+

            textStatus, errorThrown

        );

    });

    request.always(function () {

        $inputs.prop("disabled", false);

    });

    event.preventDefault();

});

</script>

  

<script>

document.getElementById("foo").addEventListener("submit", myFunction);

function myFunction() {

  alert("The message was send successfully !");

}

</script>

</html>

312 questions

91 answers

6 comments

5,034 users

5 Online Users
0 Member 5 Guest
Today Visits : 7248
Yesterday Visits : 2524
Total Visits : 6983038
...