Refresh DIV by command from server - javascript

I want to have a page that uses a mySQL database for its information, let's just say its a 0 or 1
I want the page to auto refresh a div with the value 0 or 1 from the database at a specific interval.
But I would like anyone who is viewing the page to get the same information at the same time. So I would like the server to be in charge of the interval.
How could I do this?

There are several possibilities:
1) Websockets is the latest of the technologies. If you really want near realtime update of the page and have an Infrastructure providing the possibilities, that is the way to go
2) Comet or long polling would be a second alternative
3) The most primitive - but working - startingpoint would be to constantly poll your server. Stackoverflow Article

You can use a JavaScript timer that will check server for any updates and return updated values to the client using Ajax. You can use setTimeout() function as given here:Jquery/Ajax call with timer
A sample you can try
(function worker() {
$.get('ajax/test.html', function(data) {
// Now that we've completed the request schedule the next one.
$('.result').html(data);
setTimeout(worker, 5000);
});
})();

Related

How to run asynchronous tasks for multiple users

So I've this project for school who is about "triggers" for social networks.
Let me explain:
- A user can register for our application and login
- He can sign in for multiple services like Facebook, Twitter etc.
- Then their is what we call triggers, once he signed in on our application and registered his services, everytime he will post something on twitter for example my server will see it and post it on Facebook aswell.
I knew nothing about node.js a month ago so I'm kinda new to all this async stuff but I took some course to help myself. So far so good I can now manage users etc, (I've again some research to do with oauth).
My biggest problem is this "real-time" update on our server.
I mean I searched on the internet and saw this what we call polling (?), the idea to make request frequently to a server every X seconds.
So with a bit a sudo code this what I tought it would look like:
For each User
asynchronously watch for every update on Facebook and Twitter for
this User
So I did some research about performing request every each second and found about setInterval and setTimeout
const watchSocialMedia = setInterval(function(){
Users.forEach(user => {
User.watchAndPostAnyNewPost() //
}
}, 60000);
So I put some dummy data to illustrate.
Problem is I don't think It'll be done asynchronously ?
I mean the ideal is if I could put one time for each user a 'watcher' like saying
For each User
User.watchAndPostAnyNewPost()
where watchAndPostAnyNewPost() look like this
class User () {
...
const watchAndPostAnyNewPost = setInterval(function(){
fetchFacebook();
fetchTwitter();
}, 60000);
}
So each user have his own setInterval function running on him to check if he posted anything
Anyone can tell me if it's even possible ? :-)
Thanks a lot for reading me !!!

How can I track "online" statuses of users if a server crashes?

I have multiple heroku dynos and a chat app. When a user logs in, their status is set to "online" in MongoDB. However, if a server crashes, their status will still be set as online. How can I update the user status to be "offline" when a server crashes?
If I only had one dyno, this would be easy. I'd just update every user to be "offline" when the server starts. Unfortunately, this is not possible with multiple servers.
As per our chat and comments.
The best option is to go with checking against last activity. So seeing when the last message was sent and if it happened within the last let's say 5 minutes they are online if there were no activity mark them as offline.
Like I mentioned in the comments, if you are not storing a date_created on the messages documents you will not have to change anything because _id stores the timestamp
ObjectId("507f191e810c19729de860ea").getTimestamp()
that returns this Date object
ISODate("2012-10-17T20:46:22Z")
This answer is another option (if you are wanting to keep them as online even if they are not sending messages):
If you would like to know they are still active even when they're not jumping from page to page, include a bit of javascript to ping your server every 60 seconds or so to let you know they are still alive. It'll work the same way as my original suggestion, but it will update your records without requiring them to be frantically browsing your site at least once every five minutes.
var stillAlive = setInterval(function () {
/* XHR back to server
Example uses jQuery */
$.get("stillAlive.php");
}, 60000);

Is there any javascript-event which allows an action to be executed by the web-nav continually?

I'm trying to make a websocket using jQuery which is triggered continually after the load of the page. The idea, is to get information continually from the server and to display them into the web page without any refresh.
What kind of event is?
Any brilliant idea, please?
setInterval can be dangerous because of the timing of your http request/response. Better to used chained setTimeouts, e.g.
var tick = function() {
// do something here
$('foo').toggle();
setTimeout(tick, 1000); // wait 1 second and call again
};
tick();
I think an HTML5 Websocket is what you are looking for.
The WebSocket specification defines an API establishing "socket" connections between a web browser and a server. In plain words: There is an persistent connection between the client and the server and both parties can start sending data at any time.
http://html5rocks.com/en/tutorials/websockets/basics

Meteor.jd, realtime latency with complex pusblish/subscribe rules?

I'm playing with realtime whiteboards with meteor. My first attempt was working very well, if you open 2 browsers and draw in one of them, the other one updates in a few milliseconds ( http://pen.meteor.com/stackoverflow )
Now, my second project, is to make an infinite realtime whiteboard. The main thing that changes now, is that all lines are grouped by zones, and the viewer only subscribe to the lines in the visible zones. And now there is a dealy of 5 seconds (!) when you do something in one browser to see it happen in the other one ( http://carve.meteor.com/love ).
I've tried to add indexes in the mongo database for the fields determining the zones.
I've tried updating the Collection only for a full line (and not each time I push a new point like i my first project).
I've tried adding a timeout not to subscribe too often when scrolling or zooming the board.
Nothing changes, always a 5 seconds delay.
I don't have this delay when working locally.
Here is the piece of code responsible for subscribing to the lines you the visible area :
subscribeTimeout=false;
Deps.autorun(function () {
var vT=Session.get("visible_tiles");
var board_key=Session.get("board_key");
if (subscribeTimeout) Meteor.clearTimeout(subscribeTimeout);
subscribeTimeout=Meteor.setTimeout(subscribeLines, 500);
});
function subscribeLines() {
subscribeTimeout=false;
var vT=Session.get("visible_tiles");
console.log("SUBSCRIBE");
Meteor.subscribe("board_lines", Session.get("board_key"),vT.left,vT.right,vT.top,vT.bottom, function() {
console.log("subscribe board_lines "+Session.get("board_key"));
});
}
I've been a SysAdmin for 15 years. Without running the code, it sounds like an imposed limitation of the meteor.com server. They probably put in delays on the resources so everyone gets a fair share. I'd publish to another server like heroku for an easy deploy or manually to another server like linode or my favorite Joyent. Alternatively you could try and contact meteor.com directly and ask them if/how they limit resource usage.
Since the code runs fast/instantly locally, you should see sub-second response times from a good server over a good network.

Node.js how to keep connection between page loads

On my website I have a list of all online users, updated in real-time by node.js (I'm using now.js)
The problem is, when a user navigates my site, they of course disconnect for a couple of seconds when the new page is loading. Which means they disappear from the list for all other clients, to pop back in just seconds later.
Is there any way to set a timeout on the disconnect function, e.g. if user has not reconnected in 30 seconds, remove from the list otherwise don't?
Or if there is a better way to accomplish this? Can someone please point me in the right direction :)
EDIT:
Came up with a working solution, if anyone would like to know. On server side I have this function
nowjs.on('disconnect', function() {
everyone.now.clientDisconnected();
});
which whenever a user disconnects calls this function on the client
now.clientDisconnected = function() {
setTimeout(function() { now.serverUpdateUsers(); }, 20000);
}
So instead of updating the users right away, we wait 20 seconds. By then the user should have finished loading the new page, and no difference will show for all other clients.
The serverUpdateUsers(); is the serverside function that gathers all user data and pushes it out to all clients.
I'm not exactly sure if you can modify Socket.IO's settings with now.js (which uses Socket.IO), but if you could (not sure, never used now.js) you should set the heartbeat interval to be bigger:
https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
heartbeat interval defaults to 20 seconds

Categories

Resources