Web Development Projects

Projects

Send Form Data To Google Sheets

The integration of HTML forms with Google Sheets simplifies data collection and storage. You can efficiently manage responses without needing a database by sending form submissions directly to Google Sheets.

HTML

The following HTML defines the form that allows users to submit their name, number, and email. This form uses input fields and a text area for the user to provide information. It is styled by linking a CSS file and has a script file for form submission functionality.

<body>
  <div class="container">
    <form method="post" action="" name="contact-form">
      <h4>Contact Us</h4>
      <input type="text" name="your-name" placeholder="Name">
      <input type="text" name="your-number" placeholder="Number">
      <input type="email" name="your-email" placeholder="Email">
      <textarea name="message" rows="7" placeholder="Your Message">
      </textarea>
      <input type="submit" value="Submit" id="submit">
		</form>
	</div>
</body>

Following are some Key features of the above HTML.

  • Form Structure:
    • Text inputs for name, number, and email.
    • A textarea for users to enter a detailed message.
    • A submit button to trigger form submission.
  • User-Friendly Design: Labels are replaced with placeholders inside input fields for simplicity.
  • External File Integration: CSS and JavaScript files are linked for clean and functional design.

CSS

The CSS defines the style for this contact form, ensuring it looks professional and responsive.

*{
	box-sizing: border-box;
	padding: 0;
	margin: 0;
	font-family: 'poppins', sans-serif;
	font-size: 18px;
}
body{
	height: 100vh;
	display: flex;
	align-items: center;
	justify-content: center;
}
.container{
	width: 500px;
	padding: 30px;
	border: 1px solid #eeeeee;
	border-radius: 10px;
	background-color: #003b5b;
}
h4{
	margin-bottom: 10px;
	font-size: 24px;
	color: white;
}
input{
	width: 100%;
	padding: 10px;
	margin-bottom: 10px;
}
textarea{
	width: 100%;
	padding: 10px;
}
#submit{
	border: none;
	background-color: orangered;
	color: white;
	width: 200px;
	margin-top: 10px;
	border-radius: 5px;
}
#submit:hover{
	background-color: #333333;
}

In the above CSS, we use the following Key Features.

  • Global Reset:
    • We used * to remove default padding and margins and apply a consistent font style.
    • Applies the Poppins font family for modern aesthetics.
  • Container Styling:
    • We Centered the form vertically and horizontally in the viewport.
    • Sets a width of 500px and adds padding, border, and rounded corners.
    • Background color (#003b5b) creates contrast for better readability.
  • Form Elements:
    • Inputs and the textarea have consistent width and padding.
    • The submit button (#submit) has a standout color (orangered) that changes when hovering.

JavaScript

The JavaScript file lets this form send data to Google Sheets via the provided Google Apps Script URL. Upon successful submission, it displays a confirmation message and reloads the page.

const scriptURL = 'Your Google App Script URL'

const form = document.forms['contact-form']

form.addEventListener('submit', e => {
  
  e.preventDefault()
  
  fetch(scriptURL, { method: 'POST', body: new FormData(form)})
  .then(response => alert("Thank you! Form is submitted" ))
  .then(() => { window.location.reload(); })
  .catch(error => console.error('Error!', error.message))
})

Following are the Key Features we used in JavaScript.

  • Google Apps Script Integration:
    • Uses the fetch API to send form data as a POST request to the provided Google Apps Script URL.
    • Sends form data as FormData, which handles the data in key-value pairs.
  • Event Listener for Form Submission:
    • Prevents the form’s default behavior (e.preventDefault()) to allow custom submission logic.
    • Displays a success message using an alert after successful submission.
  • Error Handling:
    • Logs errors to the console if the submission fails.

App Script

This Apps Script handles backend processing for storing submitted form data into a Google Sheet. It provides functions to initialize the script, process incoming data, and store it securely in the correct format.

const sheetName = ''
const scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  const lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    const sheet = doc.getSheetByName(sheetName)

    const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    const nextRow = sheet.getLastRow() + 1

    const newRow = headers.map(function(header) {
      return header === 'Date' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

Following are the Key functions of App Script.

  1. Initial Setup:
    • Stores the Google Spreadsheet ID for future use.
  2. Form Submission Handling (doPost):
    • It receives form data via POST request.
    • Adds the data to the specified sheet, mapping the form fields to the sheet’s headers.
    • Adds a timestamp if the header is ‘Date.’
    • It returns a success or error response in JSON format.
  3. Error Handling:
    • It uses a lock to prevent multiple submissions from conflicting.
    • Ensures that the lock is released after processing.

Watch Video on YouTube

How To Send HTML Form Data To Google Sheets

Download The Source File

Get immediate access to the original source file with a simple click, and start customizing it to fit your needs.

HTML
CSS
JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top