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 at the right place. In this article, I show you how to connect the Firebase realtime database with the form and store the 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 the database in real-time(no delays).

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

Firebase Configuration

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 the JavaScript code of Firebase. Click on a code icon which will open a popup.

Code Icon
add-firebase-sdk

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.

It will open a popup, choose test mode, and 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 the database is empty.

realtime-database

Connect Firebase Realtime Database to Your Website Form

We are done with the Firebase setup. Next, build a form with a few fields. For instance, create the index.html and add the code below to it.

<!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>Firebase</title>
</head>
<body>
    <form method="post" id="frmContact">
        <p>
            Fullname: <input type="text" name="fullname" id="fullname" required />
        </p>
        <p>
            Email: <input type="email" name="email" id="email" required />
        </p>
        <p>
            Subject: <input type="text" name="subject" id="subject" />
        </p>
        <p>
            Message: <textarea name="message" id="message"></textarea>
        </p>
        <button type="submit" name="submit">Submit</button>
    </form>
</body>
</html>

Now to interact with the Firebase realtime database, you need to add SDK for the Firebase database. I am going to perform the following steps.

  • Import SDK of Firebase app and database.
  • Configure and Initialize the Firebase.
  • Get a reference of database.
  • On form submission, send it’s data to the realtime database.

Add the below JavaScript before the closing of the body tag.

<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-app.js";
import { getDatabase, ref, set, get, child } from "https://www.gstatic.com/firebasejs/9.6.11/firebase-database.js";

// Paste the code from Firebase
const firebaseConfig = {
    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"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Get a reference to the database service
const db = getDatabase(app);

document.getElementById('frmContact').addEventListener('submit', function(e) {
    e.preventDefault();
    set(ref(db, 'users/' + Math.random().toString(36).slice(2, 7)), {
        name: document.getElementById('fullname').value,
        email: document.getElementById('email').value,
        subject: document.getElementById('subject').value,
        message: document.getElementById('message').value
    });

    alert('Your form is submitted');
    document.getElementById('frmContact').reset();
});
</script>

Here, I am using ‘users’ as a reference and inside it, I am generating a child with a random string of 5 characters. If you didn’t create a child for ‘users’ reference, each time your data will replace the old one. By creating a random string, all submissions will be stored separately without overriding the previus one.

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 the below.

firebase-database-records

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 initialized the app. By referencing the app’s database we can read the data as follows.

// read data from firebase
const dbRef = ref(getDatabase(app));
get(child(dbRef, 'users/')).then((snapshot) => {
    if (snapshot.exists()) {
        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}`);
        });
    } else {
        console.log("No data available");
    }
    }).catch((error) => {
        console.error(error);
});

This is how one can connect the Firebase realtime database with the web app. I hope this tutorial should help you in storing and reading data from the Firebase. I would like to hear your thoughts in the comment section below.

Related Articles

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

16 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.