Breaking Ajax Poll
2016 01 May

Breaking Ajax Poll


Jessy  : “Ajax polling became the grandpa's way to make thing real time! Why aren't we doing this using socket.io this time ?”
Walter : “Look, bro. I know you wanna do things from new way but you forget we don’t have time to experiment with it! Clients want it by Tuesday and today is Friday, so technically I don’t have more than 1 day uhh..(watched his watch) 5 hr and few minutes and I am not gonna ruin my weekend just because you want to do it  with your cool way and apart from this,  ajax poll is tried and tested way for us, it worked on the past. I know it takes more time to serve the request  and uses more resources as compared to your socket.io way but we are at least sure it will work on the other side. I am not sure whether we will be able to complete it with the socket.io way”

Jessy  : “Fine! I can’t say more because I also haven't tried it but still I feel we can give it a shot. If we see I can achieve through socket.io  then it's great otherwise I am ready to sacrifice my weekends :( ”
Walter : “Cool fine by me! you have worked on node.js earlier? right ”
Jessy  : “Yeah man !”
Walter : “then it will be better for me to work on other stuff while you try your crazy things! ”
Jessy  : “Okay”
Walter : “Let's make it clear what we will do.” 
Walter : "I am gonna work on Twitter API and count the tweet which carries the required keyword and then I'll write the count in DB.. all you need to do is whenever I write in DB you trigger an event and send the new value to all the browser.  ”


Jessy searched a lot about how would he trigger an event when a write is been called and it took a lot of time to him to get anything … coming back Jessy says 
Jessy  : “Hey bro, I got a problem ! let's do it another way? I can’t find a way to trigger the event when you write on DB so we have two option either do polling on DB or keep a file which you modify if you write on DB and I will trigger even when that file is modified”
Walter : “cool! look you don’t have the time and both seem fine to me but heart says for file modify because I don’t how often will get tweets ”

Jessy  : “Okay ”
Just after 40 min! Jessy called Walter  and said 
“Bro! It’s done from my end! ”
Walter : “What ! seriously? No, you kidding! show me the code man, can’t believe it  ” 

Server.js

var fs = require('fs')
var events = require('events');
var eventEmitter = new events.EventEmitter();
var config= require('./_config.js')
var mysql= require('mysql');
var app = require('http').createServer()
var io = require('socket.io')(app);

app.listen(8880);

var con = mysql.createConnection({
  host: config.host,
  user: config.user,
  password: config.password,
  database: config.dbname
});
con.connect(function(err){
  		if(err){
    		console.log('Error connecting to Db');
    		return;
  		}
  		console.log('Connection established to DB');

	});

fs.watchFile(config.filename , (curr,prev)=>{
		if(curr.mtime > prev.mtime)
			eventEmitter.emit('write');
});
var row
var fetchDB= function(){
	con.query(config.query, function(err,rows){
 		 if(err) throw err;
 			 else{
				row=rows;
				io.emit("value",rows);
  			}
	});

}
eventEmitter.on('write',fetchDB);

eventEmitter.on('dbClose',function(){
	con.end(function(err) {
  			console.log('connection clossed');
  		});
});
var client=0;
io.sockets.on('connection', function (socket) {
		client++;
		if(row){
			socket.emit("value",row);	
		}
		else{
			con.query(config.query, function(err,rows){
 			 	if(err) throw err;
 			 	else
 			 		socket.emit("value",rows);	
 			}):
		}
		socket.on('disconnect',function(){
			clients--;
		});
});

Walter : “Oh man! Finally, you learned to make pure! (99%) but can you explain it? ”
Jessy  : “Look, the code is simple and self-explanatory still If you want I will ”
“What it does is watching the file for change in fs.watchfile() method... When the file is been modified it triggers ‘write’ event which calls fetchDB method. In the fetchDB method, a query is being executed and the data is broadcasted to all the client listening to the socket. The socket is already created and it listens to the port 8888 at the top. At the client side code, all we need is include socket.js for browser side and write the event listener for the event triggered from this code! ”

Client.html

<script type="text/javascript" src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
  var client = io.connect('http://server_DNS:port');
    client.on('value', function (data) {
    console.log(data);
  });
</script>

 

Walter : “cool! It is easy, why did  I used ajax poll earlier,  but still I have a question what the heck is in require('./_config.js') ?  ”
Jessy  : “Oops! I forgot to tell you this... It's the configuration file ”

_config.js 

var _config= {
	filename: "cool.calm",
	host:"localhost",
	user:"",
	dbname:"",
	password:"",
	query:"SELECT * FROM table_name",
	initial: "0"

}
module.exports = _config;

Walter : “Do me one more favor tell me how to set it up? ”
Jessy  : “Okay ” 
“All you need is to do is to install two dependencies”

$ npm install mysql
$ npm install socket.io

Walter: “This is coooool! man “
 

 

Latest Blogs

webshop

Drupal: The ideal solution for your e-Commerce Website

In the last few decades, the online merchandising sector has made strides at an unprecedented pace following that, the demand and emergence of many e-commerce platforms are on the rise. 

Read More

Drupal 9 Upgrade

The Roadmap to upgrade Drupal site to Drupal 9

Drupal is approaching with its next big evolution and the upcoming release that is none other than Drupal 9.

Read More

How to Choose Web Development Agencies

Points to check before choosing the right website development company

In today’s day and age, where the digital population is increasing exponentially, no credible business can or should refrain from having a strong and steady web presence.

Read More

Wordpress to Drupal

Should I plan to move my Wordpress Website into the Latest Drupal version?

If you're here, I assume you already have a website built on WordPress but you're not satisfied with it, or perhaps you're here to have a clear idea about why you should give a thought to migrating

Read More