How to Connect Firebase Realtime Database to Your Website Form

Are you looking to store your website form data in the Firebase? The Firebase realtime database is a cloud-hosted NoSQL database. In this article, I show you how to connect the Firebase realtime database with the HTML form and store the data to the Firebase. We’ll also discuss how to retrieve data from the Firebase realtime 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).

To store the data in the Firebase, I will create a simple HTML form and connect it with the Firebase realtime database. I’ll use JavaScript SDK to integrate this functionality.

But before that, it requires you to perform a few configurations on your Firebase account.

Firebase Configuration

Head over to Firebase Console and create a new project. The user can also choose an existing project. Upon creating a project you will redirect to a page where you will get the option to choose JavaScript SDK. Click on the code icon for the next steps.

get-firebase-sdk
add-firebase-sdk

Copy the code provided in the popup. It’ll require in the later part of a tutorial. From the left side menu, click on Build -> Realtime Database and create a database as prompted.

On the next screen, choose test mode, and click on the Enable button.

firebase-enable-test-mode

You will redirect to the page where you will see your realtime database. The first time you’ll see no data as the database is empty. Let’s see how to fill the database.

realtime-database

Connect Firebase Realtime Database to Your Website Form

You are done with the setup of the Firebase configuration. Next, build the HTML form with a few fields. I am adding some fields for demo purposes. Adjust your fields as per your requirement. 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. This process will involve the following steps.

  • Import SDK of Firebase app and database.
  • Configure and Initialize the Firebase.
  • Get a reference for a database.
  • On form submission, send its 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.22.1/firebase-app.js";
import { getDatabase, ref, set, get, child } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-database.js";

// Paste the code from Firebase
const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "Your_AuthDomain",
    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. You can set this value to something else. Inside this reference, I am generating a child with a random string of 5 characters. If you don’t create a child for users reference, each time your data will replace the existing one. By creating a child with a random string, all submissions will be stored separately without overriding the previous records.

Now, try to submit a form and head over to your Firebase realtime database, you should see your submitted data. It will look like the below screenshot.

firebase-database-records

Read Data from Firebase Realtime Database

You learned about writing data to the Firebase realtime database. Sometimes you may also want to read the records from the Firebase. Reading data is easy and requires only a few lines of JavaScript code. You have already initialized the app. By referencing the app’s database you 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 applications. 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. Required fields are marked *