DEV Community

Ondev Webs
Ondev Webs

Posted on

Complete Guide to Creating HTML Forms and Sending Data to Google Sheets Using API

Create a Google Sheet: First, you’ll need to create a Google Sheet to store the data from your HTML form. You can create a new Google Sheet by going to your Google Drive, clicking the “New” button, and selecting “Google Sheets”.

Set up the Google Sheets API: To use the Google Sheets API, you’ll need to create a project in the Google Cloud Console and enable the Google Sheets API. Here’s a step-by-step guide to getting started: https://developers.google.com/sheets/api/quickstart/js

Create an HTML form: Next, you’ll need to create an HTML form that collects the data you want to store in your Google Sheet. Here’s an example form that collects a user’s name and email:

<form id="my-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<br>
<button type="submit">Submit</button>
</form>

Add JavaScript to send form data to Google Sheets: Finally, you’ll need to write JavaScript code that sends the form data to your Google Sheet using the Google Sheets API. Here’s an example code that uses the gapi.client.sheets.spreadsheets.values.append method to append a new row to the Sheet:
<script src="https://apis.google.com/js/api.js"></script>
<script>
function submitForm() {
gapi.client.init({
apiKey: 'YOUR_API_KEY'
}).then(function() {
return gapi.client.load('sheets', 'v4');
}).then(function() {
var params = {
spreadsheetId: 'YOUR_SPREADSHEET_ID',
range: 'Sheet1!A1:C1',
valueInputOption: 'USER_ENTERED',
resource: {
values: [[document.getElementById('name').value, document.getElementById('email').value]]
}
};
return gapi.client.sheets.spreadsheets.values.append(params);
}).then(function(response) {
console.log(response.result);
}, function(response) {
console.error(response.result.error.message);
});
}
document.getElementById('my-form').addEventListener('submit', function(event) {
event.preventDefault();
submitForm();
});
</script>

This code uses the gapi.client.sheets.spreadsheets.values.append method to append a new row to the Sheet. You'll need to replace YOUR_API_KEY with your own API key, and YOUR_SPREADSHEET_ID with the ID of the Google Sheet you created earlier.

When the user submits the form, the submitForm function is called, which initializes the Google Sheets API, loads the Sheets API, and then appends a new row to the Sheet with the data from the form.

Learn more : https://www.instagram.com/devwebsstore/

Top comments (0)