Intro to Firebase with JavaScript and jQuery

Firebase with JavaScript and jQuery

Firebase with JavaScript and jQuery

Hey! How are you all? It had been a while since last post. Today we will go through an intro to the Firebase with JavaScript and jQuery. Here we will cover Firebase and its working with basic JavaScript and jQuery. And in the meanwhile we will create a basic contact store app using these.

Firebase?

Firebase, now part of Google, is a Cloud Services Provider for Backend as a Service. They provide realtime database for the App Development on the various platforms through APIs.

New Firebase API:


Auth schemes in new Google Firebase:
http://time2hack.com/2016/06/auth-schemes-in-google-firebase.html

Why do we need Firebase or Similar System?

You might have gone through the time consuming task of getting a database ready and then synchronizing data on the application for all users. And if the application is spanning to multiple platforms along with multiple user, I can assume a lot of time spent in preparing the Realtime and Synchronous state of the system.

So if you have a online DBMS, it will save you from setup and getting started time.

And if you have realtime communication API, it will save you from the effort to figure out an architecture and system design to do the same.

Now if these above two thing are available in one, what else do we need?
Within no time you can make a Good Logical Thoughtful Idea to an Awesome working Idea.

And for a plus, if that DBMS already provides you the very common authentication schemes, Icing on the Cake. Within a small development time your Awesome Idea became an WOW! What an Idea!.

So enough with the praises; lets come to “Getting Started with Firebase” thing.

First you need to signup at Firebase. For this you can go to https://www.firebase.com/signup/ directly and finish the signup.

<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>

As soon as you sign up, it will take you to its account dashboard and provide you a readymade ‘My First App’ Database. Either you use this readymade one or you can creat a new one.

To create new one you need to input the Application name and the App URL. This app url will be used later to connect to the database. I will suggest to figureout some Good name and a unique App URL for ease rememberence. This will save you from logging in to Firebase site very frequently to check the App URL.

Now we have an app URL, we can develop our app at our end and exploit the API to save and read the data. So as per the type of platform of your application, you can choose a lib of Firebase. And if there is no lib available for your favourite platform, Firebase provides REST API, so that it goes smoothly.

Here will go ahead with the Web Platform and Firebase JavaScript library.

Lets have a sample app to go through the tutorial. Contact Manager application will be good.

So firstly we will need to include the Firebase JS lib in out page, which can be done by putting thins line in our page. This fill fetch the Firebase JS Lib from CDN.

<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>

Now, I think you remember the app URL while creating the application on Firebase. using that we will create a reference to our DB by the following line of code:

var dbRef = new Firebase('Your Firebase App URL');

I have also created a contacts app, so the dataRef is like this now:

var dbRef = new Firebase('https://contactdb.firebaseio.com/');

Yes! Now the database is available to use in code. But before proceeding, you should have a little idea about JSON as the data is stored in the JSON format. So planning a data format is necessary. So lets use the following format for our DB:

contactdb : {
    contacts: [
        {
            contactId: {
                name: 'Time to Hack',
                email: 'the.time2hack@gmail.com',
                location: {
                    city: 'Internet', //can be Mumbai
                    state: 'Active Connection', //can be Maharashtar
                    zip: 000000 //can be 122001
                }
            }
        }
    ]
}

As from above format it is clear that out db has child array `contacts`. This array will hold the contact objects as a key value pair of `contactId` and `contactObject`. `contactId` is a hash generated by Firebase. Hashed are used to prevent the concurrent access and overlapped data writing.

Actual object may look like this:

{
  "contacts" : {
    "-Jl4Y4ek1Gpb1dLW9R8o" : {
      "email" : "pankaj.njoy@gmail.com",
      "location" : {
        "city" : "Gurgaon",
        "state" : "Haryana",
        "zip" : "122001"
      },
      "name" : "Pankaj Patel"
    },
    "-Jl9cQXgm_6YkdC1xgCK" : {
      "email" : "pankajnjoy@gmail.com",
      "location" : {
        "city" : "Gurgaon",
        "state" : "Haryana",
        "zip" : "122001"
      },
      "name" : "Pankaj Patel"
    }
  }
}

Lets come back to the app design. For the basic things we must be able to add and view data.

Firstly we will see how to add data. As we have already created the reference to our db; we can now create a reference to the child array `contacts` by the `child()` method. To get the new ref of child, following is the code:

var dbRef = new Firebase('https://contactdb.firebaseio.com/');
var contactsRef = dbRef.child('contacts');

Now as we have the reference to the child array `contacts`; we can push (as the object is an array) the contact object to add into this array by following code:

var dbRef = new Firebase('https://contactdb.firebaseio.com/');
var contactsRef = dbRef.child('contacts');
contactsRef
.push({
    name: 'Time to Hack',
    email: 'thetime2hack@gmail.com',
    location: {
        city: 'The Internet',
        state: 'The Internet',
        zip: '127.0.0.1'
    }
})

And the contact gets added to the Firebase App. Now there is a trigger to an event of `child_added` which will get the newly added child.

As we are working with the collection `contacts` we are having events `child_added`, `child_removed` and `child_changed`. `child_moved` event is also there but available only when working with the ordered data.

When not working with a collection, `value` event can be used for addition and changes in the data

For viewing or reading of all contacts, following code can be used. But to loop over the contacts collection we need to work with the Firebase collection iterator `forEach`. Following code will demonstarte this:

contactsRef.on("child_added", function(snap) {
    console.log(snap.val())
    snap.forEach(function(childSnapshot) {
        var key = childSnapshot.key();
        var childData = childSnapshot.val();
    });
});

So with above code we completed the C(Create) and R(Read) of the CRUD operations of our application.

Now for U(Update) and D(Delete) we can use `.set()` and `.remove()` methods. While updating data, we would need to travarse to particular key child object anf then use set method, the set method accepts new updated object to be set as new value. And after travarsal if you wanna delete that node/key, you can use the `.remove()`. Following is the example code for adding, updating and then removing a rogue/improper value.

contactsRef
    .push({
        "email" : "wrongemail@gmail.com",
        "location" : {
            "city" : "Gurgaon",
            "state" : "Haryana",
            "zip" : "122001"
        },
        "name" : "Pankaj Patel"
    })
contactsRef.on("child_added", function(snap) {
    //set the new value
    contactsRef.child(snap.key()).set({
        "email" : "morewrongemail@gmail.com",
        "location" : {
            "city" : "Mumbai",
            "state" : "Maharashtra",
            "zip" : "452001"
        },
        "name" : "Pankaj"
    });
    //delete the object after 10 seconds
    setTimeout(function () {
        contactsRef.child(snap.key()).remove();
    }, 10*1000 );
});

So till now we went through all CRUD operations with our Firebase Data. Let’s put all bricks together to shape our contacts store application. To build a quick and easy UI, we are using Twitter Bootstrap here. You can also go through the Getting Started article of Twitter Bootstrap at Time to Hack. Following is the HTML for Form to add contact data and List of Contacts:

And the script that will have all functionality of our app is as follows:

And following script is same as above, but has jQuery code instead of plain JavaScript:

In this app, we would not go ahead with the update and delete functionality. You may give it a try and tell us about it in the comments. For the demo of the app and download of source code, you may follow following links. Happy Coding…!!!

Demo  Download



One thought on “Intro to Firebase with JavaScript and jQuery

Got Something To Say:

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

*