A simple web project to understand the integration of firebase with web for data storage
Steps: Contact form
- Login to firebase account
- Go to console
- Create project
- Click on real time database
- Use locked mode for security
- Click rules and set write to true
- Do the same for Firestore database
- This will create a cloud firestore for your database
- Chance allow read,write if false; To allow read : if false; allow write: if true;
- Go to home and click on </> web
- Name the app
- In html, add the cdnjs link of firebase in script tag: https://cdnjs.cloudflare.com/ajax/libs/firebase/10.1.0/firebase-app.js
- Copy the Use a <script> tag part
- Paste firebase config part in mail.js
- Initialize app by : firebase.initializeApp(firebaseConfig);
- Reference your database: var contactFormDB = firebase.database().ref(‘contactForm’)
- Add event listener to your form: document.getElementById("contactForm").addEventListener("submit", submitForm);
- Implement the submitForm callback function: function submitForm(e) { e.preventDefault();
var name = getElementVal("name"); var emailid = getElementVal("emailid"); var msgContent = getElementVal("msgContent");
saveMessages(name, emailid, msgContent); // enable alert document.querySelector(".alert").style.display = "block"; // remove the alert setTimeout(() => { document.querySelector(".alert").style.display = "none"; }, 3000); // reset the form document.getElementById("contactForm").reset(); }
- Define the saveMessages function that will save the data to the firebase: const saveMessages = (name, emailid, msgContent) => { var newContactForm = contactFormDB.push();
newContactForm.set({ name: name, emailid: emailid, msgContent: msgContent, }); };
- Define the getElementVal function used earlier: const getElementVal = (id) => { return document.getElementById(id).value; };