Spaces:
Running
Running
File size: 2,205 Bytes
0a30e67 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
```javascript
// Google Apps Script to save form data to Google Sheet
// Deploy as a web app with these permissions:
// Execute as: Me
// Who has access: Anyone
const SHEET_ID = '12_0SbhoTQmgXFRLhyxXDoKxQNnvYGaVCc-Glmyqzbc0';
const SHEET_NAME = 'FormSubmissions'; // change if your sheet tab name is different
function doPost(e) {
try {
const data = e.parameter;
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
// Get headers if sheet is empty
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
let nextRow;
if (headers.length === 0 || headers[0] === '') {
// First time setup - create headers
const newHeaders = ['Timestamp', 'Name', 'Email', 'Phone', 'Country'];
sheet.getRange(1, 1, 1, newHeaders.length).setValues([newHeaders]);
nextRow = 2;
} else {
nextRow = sheet.getLastRow() + 1;
}
// Prepare data row
const timestamp = new Date();
const rowData = [
timestamp,
data.name,
data.email,
data.phone,
data.interest
];
// Add data to sheet
sheet.getRange(nextRow, 1, 1, rowData.length).setValues([rowData]);
// Return success response
return ContentService.createTextOutput(
JSON.stringify({result: 'success', row: nextRow})
).setMimeType(ContentService.MimeType.JSON);
} catch (error) {
// Return error response
return ContentService.createTextOutput(
JSON.stringify({result: 'error', error: error.toString()})
).setMimeType(ContentService.MimeType.JSON);
}
}
```
To implement this:
1. Create a new Google Sheet and note its ID from the URL
2. Create a new Google Apps Script (Extensions > Apps Script)
3. Paste the google-script.js code and replace SHEET_ID with your actual sheet ID
4. Deploy the script as a web app (Publish > Deploy as web app)
5. Copy the web app URL and replace YOUR_GOOGLE_SCRIPT_ID in the index.html form script
6. The form will now submit data to your Google Sheet when submitted
The form includes:
- Loading state during submission
- Success/error messages
- Form reset on success
- Basic validation through required fields |