DEV Community

Developers Today
Developers Today

Posted on

Connecting the Registration Form To Firebase

Firebase is a mobile and web development platform that provides programmers with a variety of tools that helps them develop quality applications. In this tutorial, we are going to see how we can use firebase for our registration forms.

We can divide the whole tutorial into the following outlines:-
Create an Html template for the registration form.
Add CSS for design and responsiveness.
Connect Firebase Realtime Database to Registration Form using Javascript
1-Create the Html template for the registration form

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ContactForm</title>
    <link rel="stylesheet" href="contact_form.css">
    <link rel='shortcut icon' type='image/x-icon' href='./favicon.ico' />
    <script src="https://www.gstatic.com/firebasejs/9.9.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.9.1/firebase-database.js"></script>
</head>

<body>
    <div class="container">
        <div class="count">
            <h3>Contact Form</h3>
        </div>

        <form id="form_contact" name="contact_form">
            <label>First Name</label>
            <input name="first_name" id="fname" type="text" required placeholder="" />
            <br>
            <label>Last Name</label>
            <input name="last_name" id="sname" type="text" required placeholder="" />
            <br>
            <label>Email</label>
            <input name="email" id="email" type="email" required placeholder="" />
            <br>
            <label>Message</label><br>
            <textarea name="message" id="message" cols="30" rows="10" placeholder="Enter your message here ..." required> </textarea>
            <div class="center">
                <input type="submit" value="Submit">
            </div>
        </form>
    </div>
    <script src="contact_form.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

you can make changes according to your need in the HTML form.

2-Add CSS for design and responsiveness
This contact_form.css file is included in the HTML file.

@import url("https://fonts.googleapis.com/css?family=Roboto:400");

/* Set font of all elements to 'Roboto' */

* {
    font-family: 'Roboto', sans-serif;
    font-weight: 400;
}


/* Remove outline of all elements on focus */

*:focus {
    outline: 0;
}

body {
    background: #0d1316;
    /* Set background color to #263238*/
}

h3 {
    text-align: center;
}


/* Add styles to 'container' class */

.container {
    padding: 12px 24px 24px 24px;
    margin: 48px 12px;
    background: #109bff;
    border-radius: 4px;
}


/* Add styles to 'label' selector */

label {
    font-size: 0.85em;
    margin-left: 12px;
}


/* Add styles to 'input' and 'textarea' selectors */

input[type=text],
input[type=email],
textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
    margin-top: 6px;
    margin-bottom: 16px;
    resize: vertical;
}


/* Add styles to show 'focus' of selector */

input[type=text]:focus,
input[type=email]:focus,
textarea:focus {
    border: 1px solid green;
}


/* Add styles to the submit button */

input[type=submit] {
    background: #02060a;
    margin: 0 auto;
    outline: 0;
    color: white;
    border: 0;
    padding: 12px 24px;
    border-radius: 4px;
    transition: all ease-in-out 0.1s;
    position: relative;
    display: inline-block;
    text-align: center;
}


/* Add styles for 'focus' property */

input[type=submit]:focus {
    background: #A5D6A7;
    color: whitesmoke;
}


/* Style 'hover' property */

input[type=submit]:hover {
    background: #b13efd;
}


/* Align items to center of the 'div' with the class 'center' */

.center {
    text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

3-Connect Firebase Realtime Database to Registration Form using Javascript
For connecting to the firebase, we need to visit the following website. Then click on Add project, provide a name to the project and continue. Now it will create a project for you. (You can refer to this.)

You will get the option of selecting between the Realtime Database and the Cloud Firestore. In this tutorial, we will make use of the Real-time database. Click on the build from the left menu and chose Realtime database and set up the database.

Chose Project overview from the left menu and chose web app, create one, and copy the firebaseConfig value and paste that into the js file.

var firebaseConfig = {
    apiKey: "AIzaSyBZS2UBi3VNk8uLZ9mdJfE6KRiZjcmxZiQ",
    authDomain: "contact-form-2475b.firebaseapp.com",
    databaseURL: "https://contact-form-2475b-default-rtdb.firebaseio.com",
    projectId: "contact-form-2475b",
    storageBucket: "contact-form-2475b.appspot.com",
    messagingSenderId: "9283608547",
    appId: "1:9283608547:web:51d2956027f8b49bdd4ad6",
    measurementId: "G-5C2FQ0LQ74",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//Reference messages collection
let messagesRef = firebase.database().ref("messages");

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

//save message to firebase
function saveMessage(fname, sname, email, message) {
    let newMessageRef = messagesRef.push();
    newMessageRef.set({
        fname: fname,
        sname: sname,
        email: email,
        message: message,
    });
}


function submitForm(e) {
    e.preventDefault();

    // get Values
    let fname = getInputVal("fname");
    let sname = getInputVal("sname");
    let email = getInputVal("email");
    //   let phone = getInputVal("phone");
    let message = getInputVal("message");

    //save message

    saveMessage(fname, sname, email, message);
    window.alert("You have successfully sent your message")
        //clear form
    document.getElementById("form_contact").reset();

}

//listen to form
document.getElementById("form_contact").addEventListener("submit", submitForm);
Enter fullscreen mode Exit fullscreen mode

Be careful that all files are in the same folder, or You can change the path of the files.
Image description

Note: If you discover your data is not sent to your database, check your console. If you see any error saying permission denied, then you have to go back to your settings in firebase. Click on the database section in your sidebar, in there you will see Rules. Once you click on Rules, set the read and write to true:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}
Enter fullscreen mode Exit fullscreen mode

You can also visit my github profile.

Top comments (0)