简体   繁体   中英

Sending data from HTML form to Google Sheets

I am currently trying to implement a very simple email list system based on David McCoy's article. https://medium.com/@dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175

Although I have come across some similar questions on Stackoverflow I still cannot spot what is going wrong on my code.

Here is my HTML form:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML Form to Google Sheets</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="./css/teste.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    </head>
    <body>
        <section class="container">

            <div class="fundo">

                <form id="reset" name="subscriptionform">

                    <label>Email
                    <input type="email_submit" 
                    id="email_submit" name="email" class="feedback-input" 
                    placeholder="Email" required>
                    </label><br>

                    <input type="submit" value="ENVIAR" id = "submit">
                </form>
            </div>

            <script>
            $('#subscriptionform').submit(function(e){
                    e.preventDefault();
                    formSubmit();
                })

                function formSubmit(){
                    var emailSubmitName = $('#email_submit').val();
                    if (emailSubmitName != ''){
                        var $form = $("#subscriptionform"),
                            url='https://(...)'
                        $.ajax({
                            url: url,
                            method: "GET",
                            dataType: "json",
                            data: $form.serializeObject(),
                            success: function(response){
                                $('#subscriptionform')[0].reset();
                                return true
                            } 
                        })
                    }
                    else{
                        return false
                    }
                }
            </script>

        </section>
    </body>
</html>

And here is the Web app code I copy and paste on my Google Sheet: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6#file-google_script-gs

// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-

script-using-postget-methods-with-ajax-example/

function doGet(e){
  return handleResponse(e);
}

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

Thanks in advance for your attention!

In order to get the form object you need to use #reset as selector[1] instead of #subscriptionform , because "reset" is the id of the form element. Change this:

$('#subscriptionform') 

For this:

$('#reset')

[1] https://www.w3schools.com/jquery/jquery_ref_selectors.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM