.
.
INSERT INTO Google Sheet with Google Apps Script using POST/GET methods (with ajax example)
1) Create Google Sheet
2) Add App Script
2.1) Paste the following script
// 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()); } |
2.2) Run Setup function
2.3) Allow the apps to run.
2.4) Publish Codes
3) Create Front-End HTML and JavaScript
(This demo is using a CodePen Editor)
HTML
<script data-cfasync="false" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="foo"> <p><label for="name">Name:</label> <input id="name" name="name" type="text" value="" /></p> <p><label for="comment">Comment:</label><br/> <textarea id="comment" name="comment" cols="40"></textarea></p> <p id="result"></p> <input type="submit" value="Send" /> </form> |
JS
jQuery( document ).ready(function( $ ) {
// variable to hold request var request; // bind to the submit event of our form $("#foo").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); $('#result').text('Sending data...'); // fire off the request to /form.php request = $.ajax({ url: "<YOUR CODE URL>", type: "post", data: serializedData }); // callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ // log a message to the console $('#result').html('<a href=<YOUR SHEET URL>?usp=sharing" target="_blank">Success - see Google Sheet</a>'); console.log("Hooray, it worked!"); }); // 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 occured: "+ 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(); }); }); |
CodePen Demo:
Reference:.
.
No comments:
Post a Comment