How to Connect Firebase Realtime Database to Your Website Form

Are you looking to store your website forms data to the Firebase? If yes, then you are in the right place. In this article, I show you how to connect the Firebase realtime database with the form and store its data to the Firebase.

The Firebase realtime database is a cloud-hosted NoSQL database. In Firebase, data is stored as JSON and synchronized in real-time with all connected clients built using iOS, Android, and JavaScript SDKs. When we say real-time it means data exchanged between applications and database in real-time(no delays). You can read more about Firebase features on their documentation.

For this tutorial, I will create a simple contact form and store the form data to the Firebase realtime database. To send data from the form to the Firebase I’ll use JavaScript SDK.

Firebase Configuration

In order to get started, head over to Firebase Console and create a new project. The user can choose an existing project as well. Once you create a new project you will redirect to a page where you would get JavaScript code of Firebase. Click on a code icon which will open a popup.

Code Icon
popup

Copy the code shown in the popup which requires in the next steps. From the left side menu, click on ‘Database’ and then on ‘Create database’ under the Realtime Database section.

create Firebase database

It will open a popup, choose test mode, and finally click on the ‘Enable’ button.

Test Mode

You will redirect to the next screen where you will see your realtime database. Right now there is no data so your database is empty.

realtime-database

Connect Firebase Realtime Database to Your Website Form

We are done with the Firebase setup. The next thing that needs to do is create a form and store form data to the Firebase. Let’s build a simple contact form on top of Bootstrap. Create a file index.html and add the below code in it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Firebase</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
    <div class="row">
        <div class="container">
            <h2>Contact Form</h2>
            <div class="alert alert-success success-message" style="display:none;">Form submitted successfully.</div>
            <form id="contactForm">
                <div class="form-group">
                    <label for="exampleFullName">Full Name</label>
                    <input type="text" class="form-control fullname" id="exampleFullName" placeholder="Enter Full Name" required>
                </div>
                <div class="form-group">
                    <label for="exampleEmail">Email</label>
                    <input type="email" class="form-control email" id="exampleEmail" placeholder="Enter Email" required>
                </div>
                <div class="form-group">
                    <label for="exampleSubject">Subject</label>
                    <input type="text" class="form-control subject" id="exampleSubject" placeholder="Enter Subject" required>
                </div>
                <div class="form-group">
                    <label for="exampleMessage">Message</label>
                    <textarea class="form-control message" id="exampleMessage" placeholder="Enter Message" cols="30" rows="10" required></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-database.js"></script>
    <script src="js/main.js"></script>
</body>
</html>

In the above code, I included a Firebase JS file before main.js which I copied before plus the JS of Realtime Database. Create a main.js file under the ‘js’ folder. This JS file will have actual logic to interact with the Firebase. Add the copied code from Firebase at the top of main.js file.

// Paste the code from Firebase
var config = {
    apiKey: "YOUR_API_KEY",
    authDomain: "Your_AuthDomain",
    databaseURL: "YOUR_DATABAE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID"
};
firebase.initializeApp(config);

After this create a collection under which your form data would store. You can give any name to the collection. In my case, I create a collection called ‘contactformmessages’.

// Reference messages collection
var messagesRef = firebase.database().ref('contactformmessages');

Finally, we will take all form values and pass them to the Firebase on the form submission in the following way.

$('#contactForm').submit(function(e) {
    e.preventDefault();

    var newMessageRef = messagesRef.push();
    newMessageRef.set({
        name: $('.fullname').val(),
        email: $('.email').val(),
        subject: $('.subject').val(),
        message: $('.message').val()
    });

    $('.success-message').show();

    $('#contactForm')[0].reset();
});

Now, try to submit a form with dummy values and head over to your Firebase realtime database, you should see your data stored in the database. It will look like below.

form data

Read Data from Firebase Realtime Database

You got to learn about writing data to the Realtime Database of Firebase. You may also want to read it from Firebase. Reading data from Firebase is easy and requires only a few lines of JavaScript code. We have created a message collection as messagesRef. Using this variable you can read data as follows.

messagesRef.once('value').then((snapshot) => {
    Object.keys(snapshot.val()).forEach((key) => {
        console.log(`Name: ${snapshot.val()[key].name}`);
        console.log(`Email: ${snapshot.val()[key].email}`);
        console.log(`Subject: ${snapshot.val()[key].subject}`);
        console.log(`Message: ${snapshot.val()[key].message}`);
    });
});

I hope you learned about connecting Firebase to the website form. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

15 thoughts on “How to Connect Firebase Realtime Database to Your Website Form

  1. I know things may have changed with firebase since this was written but no matter what I cant get this to add the form content to the database and I have been through tutorial numerous times and have no console errors. I have updated the firebase version to the latest, permissions are true for read and write, js folder was created with main.js inside. It should work unable to figure out why.

  2. I’ve created this exactly as you’ve described, but no data is being stored in the DB?

    I’ve changed rules to be true, true.

    But nothing is coming through.

    Any ideas?

    1. Same, This is not posting any data for me as well. I don’t have any errors on inspection. Please help!

  3. Thanks Sajid this works. but still updating firebase version to 7.7.0 (currently latest) in the source code made it work for me.

  4. It doesn’t work for me. I get this error message on console:

    TypeError: firebase.database is not a function

    It refers to:

    var messagesRef = firebase.database().ref(‘contactformmessages’);

    How can I fix it?

    Thanks

  5. Hola buenas tardes

    Me puede ayudar a entender en que archivo dejo esta lineas de comandos en index.html o en main.js ?

    ¿ index.html o main.js ?
    var messagesRef = firebase.database().ref(‘contactformmessages’);

    y este otro ?

    $(‘#contactForm’).submit(function(e) {
    e.preventDefault();

    var newMessageRef = messagesRef.push();
    newMessageRef.set({
    name: $(‘.fullname’).val(),
    email: $(‘.email’).val(),
    subject: $(‘.subject’).val(),
    message: $(‘.message’).val()
    });

    $(‘.success-message’).show();

    $(‘#contactForm’)[0].reset();
    });

    donde la ubico para poder probar este formulario con firebase,
    de ante mano muchas gracias

Leave a Reply

Your email address will not be published. Required fields are marked *