Building a Dynamic Contact Form with Firebase Realtime Database
Chabba Saad
Posted on May 9, 2024
Building a Dynamic Contact Form with Firebase Realtime Database
In this tutorial, we'll walk through the process of creating a dynamic contact form using Firebase Realtime Database. This form not only captures user inputs but also allows you to view, edit, and delete messages directly from a web interface. This is particularly useful for managing user feedback or queries efficiently.
*Note *: Before we start our tutorial dont forget to allow permission read and write in our realtime Database
Prerequisites
To follow along, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you'll need access to Firebase and a project set up with Firebase Realtime Database enabled.
Step 1: Setting Up Your HTML Structure
First, we define the HTML structure. This includes a simple form for user inputs and a table to display the stored messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Messages | Firebase</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div class="container">
<table id="messagesList"></table>
</div>
<div class="container">
<form action="" id="contactForm">
<div class="alert">Your message sent</div>
<div class="inputBox">
<input type="text" id="name" placeholder="Your name...." />
<input type="email" id="emailid" placeholder="Your Email....." />
<textarea id="msgContent" cols="30" rows="10" placeholder="Message"></textarea>
<input id="date" type="date" ></input>
<button type="submit" id="submit-button">Submit</button>
</div>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/firebase/7.14.1-0/firebase.js"></script>
<script src="./mail.js"></script>
</body>
</html>
Step 2: Firebase Configuration and Initialization
Before interacting with Firebase, we need to configure and initialize it within our application. This involves setting up the Firebase connection and referencing the specific database path.
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Reference your database
var contactFormDB = firebase.database().ref("contactForm");
Step 3: Fetching and Displaying Messages
We use the fetchMessages function to listen for real-time updates from Firebase. Any changes in the database will automatically update the HTML table.
// Fetch and display messages
function fetchMessages() {
contactFormDB.on('value', function(snapshot) {
document.getElementById('messagesList').innerHTML = '<tr><th>Name</th><th>Email</th><th>Message</th><th>Date</th><th>Actions</th></tr>';
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
document.getElementById('messagesList').innerHTML += `<tr id="${childKey}">
<td>${childData.name}</td>
<td>${childData.emailid}</td>
<td>${childData.msgContent}</td>
<td>${childData.date}</td>
<td>
<button onclick="deleteMessage('${childKey}')">Delete</button>
<button onclick="editMessage('${childKey}', '${childData.name}', '${childData.emailid}', '${childData.msgContent}')">Edit</button>
</td>
</tr>`;
});
});
}
Step 4: Editing and Deleting Messages
Editing and deleting functionality is crucial for managing the entries. The editMessage function populates the form with existing data, while deleteMessage removes the entry from Firebase.
// Delete a message from Firebase
function deleteMessage(id) {
contactFormDB.child(id).remove();
}
// Populate form with message data for editing
function editMessage(id, name, email, message) {
document.getElementById('name').value = name;
document.getElementById('emailid').value = email;
document.getElementById('msgContent').value = message;
// Set current editing ID to enable
currentEditingId = id;
}
// Update an existing message in Firebase
function updateMessage(id) {
var updatedName = document.getElementById('name').value;
var updatedEmail = document.getElementById('emailid').value;
var updatedMessage = document.getElementById('msgContent').value;
var updatedDate= document.getElementById('date').value;
contactFormDB.child(id).update({
name: updatedName,
emailid: updatedEmail,
msgContent: updatedMessage
date: updatedDate
});
// Clear form after update
clearForm();
}
// Clear form fields and reset editing state
function clearForm() {
document.getElementById("name").value = '';
document.getElementById("emailid").value = '';
document.getElementById("msgContent").value = '';
document.getElementById("date").value = '';
// Reset to "add new" mode
currentEditingId = null;
}
Step 5: Handling Form Submissions
To handle form submissions, we distinguish between adding a new message and updating an existing one based on whether an ID is set in currentEditingId.
// Handle form submission for new or updated messages
document.getElementById("contactForm").addEventListener("submit", submitForm);
function submitForm(e) {
e.preventDefault(); // Prevent default form submission
var name = document.getElementById("name").value;
var emailid = document.getElementById("emailid").value;
var msgContent = document.getElementById("msgContent").value;
var date = document.getElementById("date").value;
// Check if we're updating an existing message or adding a new one
if (currentEditingId) {
updateMessage(currentEditingId, name, emailid, msgContent, date);
} else {
saveMessages(name, emailid, msgContent, date);
}
}
// Save a new message to Firebase
function saveMessages(name, emailid, msgContent, date) {
var newContactForm = contactFormDB.push();
newContactForm.set({
name: name,
emailid: emailid,
msgContent: msgContent,
date: date
});
}
Fetch messages initially
fetchMessages();
Conclusion
This tutorial provides a comprehensive guide on creating a dynamic web-based contact form using Firebase Realtime Database. With real-time data syncing, editing, and deletion capabilities, managing contact form submissions becomes streamlined and efficient. Remember to replace the placeholder values in the Firebase configuration with your actual Firebase project settings.
Posted on May 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.