Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Contact form with Firebase


In today's digital world, having a reliable contact form is crucial for businesses. Whether you're looking to gather feedback, field inquiries, or connect with potential clients, a well-designed contact form can make all the difference. This guide explores how to take your existing contact form and integrate it with the Firebase platform, allowing you to store and manage user submissions with ease.


Using Firebase as the backend for a website's contact form offers several benefits. Firstly, it eliminates the need for hosting a separate server for the backend, thereby reducing website costs. Additionally, Firebase removes the requirement for an email service to receive emails containing client messages from the contact form. Instead, the inputs are directly stored in the Firebase database, specifically Firestore. This allows you to easily view user queries. Furthermore, you can also connect a custom mobile application to fetch and view client queries directly on your mobile devices.

Contact Form Frontend

Starting point is a responsive, sample contact form of website built using html and css.



<html lang="en" dir="ltr">
  <head>
      <style media="screen">
        /* Style inputs */
          input[type=text], input[type=email], textarea {
          width: 100%;
          padding: 12px 20px;
          margin: 8px 0;
          display: inline-block;
          border: 1px solid #ccc;
          border-radius: 4px;
          box-sizing: border-box;
        }

        /* Style the submit button */
        button {
          width: 100%;
          background-color: #4CAF50;
          color: white;
          padding: 14px 20px;
          margin: 8px 0;
          border: none;
          border-radius: 4px;
          cursor: pointer;
        }

        /* Add a background color to the submit button on mouse-over */
        input[type=submit]:hover {
          background-color: #45a049;
        }
      </style>
  </head>
  <body>
    <form>
      <label for="email">email</label>
      <input type="email" id="email" name="email" placeholder="Your email..">
      <label for="message">Message</label>
      <textarea id="message" name="message" placeholder="Write something.." style="height:200px"></textarea>
      <button id="submit_msg" type="button">Submit</button>
    </form>
  </body>
</html>

The next step is connecting it to backend  – Firebase.

Introducing Firebase

Firebase is a cloud platform provided by Google that offers a wide range of services, including a real-time database, authentication, hosting, and more. For our contact form, we will use Firebase's Firestore database to store and view the messages submitted by users.


To get started, you'll need to create a Firebase account and set up a new project. This process is straightforward and can be done directly through the Firebase console. Once you've created your project, you'll be provided with the necessary script to connect Firebase with your application.


Connecting to Firebase

With the Firebase project set up, it's time to integrate it with our contact form. We'll be using vanilla JavaScript, to handle the form submission and data storage.

Capturing Form Submissions

First, we'll add event listener to our contact form to listen for the submit event. When the form is submitted, we'll prevent the default form submission behavior and instead capture the input values from the form fields by creating a helper function called getInputValue that takes the ID of an input tag and returns its corresponding value. This will retrieve the name, email, phone, and message data entered by the user.

Sending Data to Firebase

With the form data collected, create a function called saveMessage that will send data to the Firebase firestore database. This function will take the form field values as parameters and use the Firebase SDK to push the data to a collection named "messages" in the firestore.

Now in order to ensure that the data can be written to the database, we'll need to update the Firebase rules to allow public write access. This is a necessary step, as by default, Firebase requires authentication for any data modifications. For this, inside the frestore database go to the rules tab and update the rules as follows:

Firestore rules


After the form has been successfully submitted, we'll want to provide the user with some feedback to let them know that their message has been delivered. This can be done by displaying a temporary alert message that will disappear after a few seconds.

To achieve this, create a new html element with a class of 'alert' and use JavaScript to toggle its visibility. The alert message indicating successful submission will be displayed immediately after the form data is saved to Firebase, and then it will automatically hide after 3 seconds.

Clearing the Form

Finally we'll clear the form fields after the message has been successfully submitted. This can be done by calling the reset() method on the form element.


The complete JavaScript code is given below, Replace config with the firebase config values present in project settings:

const config = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};
firebase.initializeApp(config);

var db = firebase.firestore();

//Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);

//submit form
function submitForm(e){
    e.preventDefault();
    // Get values
    var name = getInputValue('name');
    var email = getInputValue('email');
    var message = getInputValue('message');

    //save message
    saveMessage(name, email, message);
    // Show alert
    document.querySelector('.alertForm').style.display = 'block';
    // Hide alert after 3 seconds
    setTimeout(function () {
        document.querySelector('.alertForm').style.display = 'none';
    }, 3000);
    // Clear form
    document.getElementById('contactForm').reset();
   
}

// Function to get form values
function getInputValue(id){
    return document.getElementById(id).value;
}

// Save message to firebase
async function saveMessage(name, email, message) {
    const userRef = db.doc(`messages/${email}`)
    if (await userRef.get().then((docSnapshot)=>docSnapshot.exists)) {
        await userRef.update({
            message: firebase.firestore.FieldValue.arrayUnion(`${message}`)
        })
    }
    else {
        await userRef.set({
            name,
            email,
            message: firebase.firestore.FieldValue.arrayUnion(`${message}`)
        })
    }
}

Conclusion

By following the steps outlined in this guide, you can connect your contact form to the Firebase platform. This integration will allow you to easily store and view form submissions.

Remember, that specific firebase initialization data and API keys will be unique to your project, so be sure to replace the placeholders in the code with your own values. And if you have any further questions or need additional assistance, don't hesitate to reach out to the Tech Solutions community for support. 

Post a Comment

0 Comments

Ad Code

Responsive Advertisement