In this article, we’ll walk you through adding data to Firebase Realtime Database using a simple HTML form and JavaScript. Firebase is a powerful platform that lets you build scalable applications without worrying about the backend. If you’re new to Firebase, check out this tutorial to learn how to host your website for free with Firebase Hosting.
For this tutorial, we will add a product to the Realtime Database using an HTML form. We’ll be working with a simple form to collect the product’s details like name, price, quantity, and image URL, and then we’ll use JavaScript to push the data to Firebase.
Project Setup
Before we dive into the code, ensure you have Firebase set up in your project. You should have already followed the steps to initialize Firebase as shown in our previous tutorial. If not, make sure to visit the Firebase console and add Firebase to your web project.
Now, let’s create a new page in our project called addproduct.html
, where we will create a form to collect the product’s information.
1. addproduct.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Product</title>
<link rel="stylesheet" href="styles.css"> <!-- Include your CSS for styling -->
</head>
<body>
<div class="form-container">
<h2>Add a New Product</h2>
<form id="articleForm">
<div class="form-group">
<label for="nomArticle">Product Name</label>
<input type="text" id="nomArticle" name="nomArticle" placeholder="Enter product name" required>
</div>
<div class="form-group">
<label for="prix">Price</label>
<input type="number" id="prix" name="prix" placeholder="Enter product price" required>
</div>
<div class="form-group">
<label for="quantite">Quantity</label>
<input type="number" id="quantite" name="quantite" placeholder="Enter quantity" required>
</div>
<div class="form-group">
<label for="images">Image URL</label>
<input type="text" id="images" name="images" placeholder="Enter image URL" required>
</div>
<button type="submit" class="btn">Save Product</button>
</form>
</div>
<script src="formHandler.js"></script> <!-- Include your JavaScript file -->
</body>
</html>
2. Firebase Configuration (config.js
)
Next, let’s configure Firebase for your project. This file will contain your Firebase project credentials.
// Import the functions from Firebase SDK
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js";
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-database.js";
// Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const database = getDatabase(app);
Replace the placeholder values like YOUR_API_KEY
with the actual values from your Firebase project settings.
3. Handling Form Submission (formHandler.js
)
This is where the magic happens! We will listen for the form submission event and send the data to Firebase Realtime Database.
import { database, ref, push, set } from './config.js';
// Get the form element
const form = document.getElementById('articleForm');
form.addEventListener('submit', function (e) {
e.preventDefault();
// Collect form data
const nomArticle = document.getElementById('nomArticle').value;
const prix = document.getElementById('prix').value;
const quantite = document.getElementById('quantite').value;
const images = document.getElementById('images').value;
// Reference to Firebase Database
const reference = push(ref(database, 'articles'));
// Save data to Firebase
set(reference, {
nomArticle: nomArticle,
prix: prix,
quantite: quantite,
images: images
}).then(() => {
alert('Product added successfully!');
form.reset(); // Reset the form after submission
}).catch((error) => {
console.error("Error adding product: ", error);
});
});
How It Works
- Form Submission: When the user submits the form, the JavaScript code listens for the form’s
submit
event and prevents the default form submission withe.preventDefault()
. - Firebase Reference: We create a reference to a new entry in the
articles
node of the Firebase Realtime Database using thepush
function. - Data Push: The
set
method saves the form data (product name, price, quantity, and image URL) to the Firebase Database. - Form Reset: Once the data is successfully saved, the form is reset to clear the input fields for a new entry.
Styling Your Form (Optional)
You can style your form to make it look more professional. Here’s a basic CSS example to get you started:
.form-container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #f9f9f9;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
}
.form-group input {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.btn {
padding: 10px 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.btn:hover {
background-color: #218838;
}
Feel free to modify this to suit your needs!
Conclusion
In this tutorial, you’ve learned how to create a simple HTML form and use JavaScript to add data to Firebase Realtime Database. With Firebase, you can quickly build dynamic and scalable applications.
For the complete source code of this project, you can download it here.
Now that your form is functional, you can expand this project further by adding more fields, improving validation, or even building an admin panel to manage your data!
New