Send HTML Form Data To Google Spreadsheet

Why to go with google form when you want to use your own form. Build your own html form and send all the records to google spreadsheets, here is the code and step by step procedures to submit your data in google spreadsheets. Just Follow simple steps.



1) Create Form 

Create html form and named it index.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'>
  </head>
  <body>
  <form id=form1>
      <p>
        <label>Name</label>
        <input id='name' name='name' type='text'>
      </p><p>
        <label>Email Address</label>
        <input id='emai' name='emai' type='email'>
      </p><p>
        <label>Phone Number</label>
        <input id='phone' name='phone' type='tel'>
      </p>
      
      <p>
        <label>Message</label>
        <textarea id='message' name='message' rows='5'></textarea>
      </p>
        <div id='success'></div>
        <button type='submit'>Send</button>
    </form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <!-- Custom Theme JavaScript -->
  <script src='js/google-sheet.js'></script>
  </body>
</html>

2) Create Script File

Create script file and named google-sheet.js in this js file paste below code

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#form2").submit(function (event) {

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "PASTE SCRIPT URL HERE",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR) {
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(response);
        console.log(textStatus);
        console.log(jqXHR);
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown) {
        // Log the error to the console
        console.error(
            "The following error occurred: " +
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

    // Prevent default posting of form
    event.preventDefault();
});


3) Create Google Sheet


Go to this link https://www.google.co.in/sheets/about/  -> go to google sheet -> Start A New Spreadsheet -> click on blank icon and create your new google sheet. Name this sheet as form google sheet . 

Create columns in spreadsheet below is the example add this fields in columns


nameemailphonemessage

4) Paste Script 

Now in Spreadsheet in menu go to Tools -> Click On Script Editor  New window will open there will be one open file code.js, untitled project on the top bar and named it as Form Script then paste below code in that area.



//  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.

    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());
}


After pasting this code, Now there will be save icon click on that and save, after save there is drop-down  select function click on that and select SETUP and then new window will open for authorization Required, authorize 


After Authorization go to menu bar File -> Click on Manage versions 
New dialogue box will open named it as Initial version and -> click on Save New version -> than click on OK Button

After completing this find Current project's triggers click on that, new dialogue will open click on No triggers set up link click to add

1) Below run field select doPost from dropdown
2)Events select From spreadsheet
3)Select On form submit
click on save

Go to Menu click on Publish -> Deploy as web app
Project version: 1
Execute the app as: ME 
Who has access to the app : select Anyone, even anonymous

Now click on  deploy button.
after deploy new dilogue will open there will be  Current web app URL copy that URL and paste on google-sheet.js

paste script where "PASTE SCRIPT URL HERE"

save it and run index.html fill fileds and submit button you will get your form data in google spreadsheet

Comments

Popular posts from this blog

Disable right click, Inspect Element and page source using JavaScript in Html and asp.net

Create Login With Role Using Thee Tire Architecture In Asp.Net C#