Home > Uncategorized > Broadcast data to all viewers of your webpage using Firebase

Broadcast data to all viewers of your webpage using Firebase

firebase

Firebase is a cloud-hosted JSON based database, which can be used to replace the back-end of web applications.
It excells in certain cases, using websockets to communicate seamlessless between client and server, it removes the need for postbacks or Ajax polling.

Here is a simple example using Firebase to broadcast a message to all viewers of a particular web-page. I have removed the security settings for this particular instance, so no username or password is required.

The callback is event-orientated, so whenever the value held in the database changes, the event is fired on all clients, with the snapshot object containing the updated value.

<html>
 <head>
  <script type='text/javascript' src='https://cdn.firebase.com/js/client/1.0.6/firebase.js'></script>
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script language="javascript">
    var myRootRef = new Firebase('https://vivid-fire-7206.firebaseio.com/');
    function setData()
	{		
		myRootRef.set($("#message").val());
	}
	myRootRef.on('value', function(snapshot) {	 
	  $("#lastMessage").html(snapshot.val());
	});
  </script>   
  Say something to all users viewing this page:<br>
  <input name="text" id="message" onkeyup="setData()"> 
   <br>
   <br>
   <h2 id="lastMessage"></h2>
 </head>
 <body>  
 </body>
</html>
Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: