In my html project I have a form with 3 fields. I want to store the data to firestore. I connected my project to firebase perfectly. The firebase confg for data submission was written in a separate js file.
// firebase config.
import { initializeApp } from "firebase/app";
import { addDoc, collection, getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyDgynWgeZiWXkalunthJOeNi2FbwNULK6U",
projectId: "abrahamsajan-portfolio",
messagingSenderId: "1059873599474",
appId: "1:1059873599474:web:44b9be9caf9d5efbe5c56b",
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// form submission
const form = document.querySelector(".contact-form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
const fullName = form.querySelector("#full-name").value;
const email = form.querySelector("#email").value;
const message = form.querySelector("#message").value;
try {
const docRef = await addDoc(collection(db, "enquiries"), {
fullName: fullName,
email: email,
message: message,
});
console.log("Document written with ID: ", docRef.id);
alert("Form submitted successfully!");
form.reset();
} catch (error) {
console.error("Error adding document: ", error);
alert(
"An error occurred while submitting the form. Please try again later."
);
}
});