abroadveda / google-script.js
Prajjwal13's picture
now provide a way for me to fetch details from the form to a google sheet - Follow Up Deployment
0a30e67 verified
```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