Alternatives to using meta-refesh for updating a page - javascript

In the past, when I've covered events, I've used a meta-refresh with a 5 minute timer to refresh the page so people have the latest updates.
Realizing that this may not be the perfect way to do it (doesn't always work in IE, interrupts a person's flow, restarts things for people with screen readers, etc.) I'm wondering if there's any other way to do handle this situation.
Is it possible to have something like ajax check every few minutes if the html file on the server is newer and have it print a message saying "Update info available, click here to refresh"?
If that's crazy, how about a javascript that just counts down from 5 minutes and just suggests a refresh.
If anyone could point me to tutorials or code snippets I'd appreciate. I just play a programmer on TV. :-)

Actually, your thought on a timed Ajax test is an excellent idea. I'm not sure that is exactly what StackOverflow uses, but it checks periodically to see if other answers have been posted and shows the user, on an interval, if there are updates.
I think this is ideal for these reasons:
It's unobtrusive - the reader can easily ignore the update if they don't care
It won't waste bandwith - no reloading unless the user chooses to
It's informative - the user knows there's an update and can choose to act on it.
My take on how - have the ajax script send off the latest post id to a script that checks for new scripts. This script can query your database to see if there are any new posts, and how many there are. It can return this number. If there are new posts, show some (non modal) message including the number of updates, and let the user decide what to do about it.

setInterval(function() {
if (confirm("Its Been 5 Minutes. Would you like to refresh")) {
window.location.reload(true);
//Or instead of refreshing the page you could make an ajax call and determing if a newer page exists. IF one does then reload.
}
}, 300000);

You can use the setInterval function in javascript.
here's a sample
setInterval("refresh function", milliseconds, lang);
You will use it passing a name to a function that actually refresh the page for the first param and the number of milliseconds between refresh for the second param (300000 for 5 minutes). The third parameter lang is optional

If the user would be interacting with the scores and clicking on things it would be a little rude to just refresh the page on them. I think doing something like a notification that the page has been updated would be ideal.
I would use jQuery and do an ajax call to the file on the server or something that will return the updated data. If it's newer than throw up a Growl message
Gritter - jQuery Growl System
Demo of what a Growl is using Gritter
A Growl message would come up possibly with whatever was changed, new scores and then an option within that message to refresh and view the new results.
jQuery Ajax information

Related

secure way to count video plays

I've been trying to think of ways to check the validity of plays on any given video that has been served to a user. I don't want to be updating the counter every time a user hits the play button as this could be easily abused. Not only that, the user could always visit the Ajax request page which updates the plays directly and then just click refresh until their hearts content.
For an issue I'd assume to be fairly popular, I can't seem to find anything based on the security of it.
One idea I thought might be good would be to check would be to see how much of the content has been streamed when serving the file via PHP - but according to this answer, that is impossible.
So, how should I approach this problem? Do I bite the bullet and just hope that users don't abuse the system (which they definitely will) or is there any solution to this problem?
Cheers.
EDIT: Here's an example of something I'd be looking for...
$file = new File($path);
$read = $file->read();
while($read->reading()){
// if 30 seconds has elapsed
if($read->elapsed() > 30000){
// query database
}
}

Securing/Obfuscating JavaScript API requests

I have a page that allows users to watch a YouTube video and automatically receive a reward as soon as the video ends playing. This is done with the Youtube JS API:
pseudocode:
function videoStoppedPlaying() {
requestRewardFromServer(); // currently uses an XMLHttpRequest
}
The problem with this approach is that one could just open the browser console and manually call requestRewardFromServer().
I am already applying obfuscation on the code, but this is like putting a bandage on a hole in a boat; It does not solve the problem.
Edit: So far the only solution that comes close is using timestamps. Even though this is not the ideal solution, I will take the advice to heart and try to further obfuscate the JS code.
Any suggestions?
The only solution to control that the user is actually watching the video, besides checking end time - start time vs length of video is to actually check that the user is really watching it. I suppose you have a function that can tell you at what minute of the video (or percentage) the user is. So, you could periodically inform the server via javascript about that: For example, every 5 seconds or every 5% of the video, the client has to send a xmlhttp request to the server to inform it about this. The server will check for a client that it received all requests in the corresponding order (or almost, maybe he rewatched a part of it, you will have to figure out an appropiate algorithm).
It is not easy, it requires some work and it is not quite 100% 'bulletproof'. But, anything related to javascript can still be manipulated locally.
When getting the reward, store the Youtube video ID so you get at least one reward per video. Of course you have to keep track of the video ID's or else you can pass any string.
To prevent users getting the reward without watching the video you could build some timer such that it would be impossible to get the reward after the time has exceed.
Below are my thoughts on this-
I feel you need to dive into server side for this.
Set a session variable on the server, such as video_length = some_length.
From the time the video started, send an ajax request to the server and set some session variable, as video_started = some_time.
Now, when you call requestRewardFromServer(), compare the current time with video_start. It needs to greater than or equal to the video_length.
If it is satisifes the condition, reward them, or else not. You might say this doesn't guarantee that the full video is watched. Yes, but at least the person trying to spoof has to wait that long.

What is the right way to call dynamic content (currently using ajax) inside a cached page?

We have a news website where we cache a complete article page.
There are 4 areas that need to continue to be dynamic on that page:
View Counter: We add +1 to view_counts of that article when page loads.
Header: On the header of the website we check if session->id exists or not if it does we display a Welcome [Name], My Profile / Logout and if not we show Register / Login.
Comments: We display the comments made for that article.
Track User Behavior: We track every single action made by users on the site
Now the only way we could think of doing this is through AJAX calls:
$('#usercheck').load(<?php echo "'" . base_url() . "ajax/check_header'"; ?>);
And so on.
This is creating a massive load on CPU, but what would be the right/alternative way of approaching this?
Please see attached:
First of all, you do not have to use AJAX for every possible dynamic content, especially in the case of comments, you may as well load them via an iframe.
That way, you are not relying on Javascript to make the request.
It may even work for the counter.
However, you problem is not Javascript, nor the database server, based on what I can see from your graph. It seems to me you have some heavy PHP controllers, maybe you are loading a heavy framework just to have $session->id checked.
Further, what do you mean by "we track every single action"? How do you track them? Are you sending an AJAX request from every little thing or are you debouncing them with JS and only sending them one every 30 seconds or so?
My advice is that you consider the size of the PHP code you are calling, and slim it down as much as you can, even to zero if it seems feasible (by leveraging localStorage to keep track of you user session after the first login), and maybe loading the counter and the comments in alternative ways.
For example, I infer you are only checking the counter once per page load, ignoring subsequent loads by other users while the current user is reading the article, so your counter may happen to be out-of-date once i a while, depending on your traffic.
I going to explain it better: your page has n views, so when I load it, you request for n and then display n+1 to me. While I'm reading, the same page gets requested and viewed x times by other users. Your counter on the server has been surely updated to n+x, but the counter on my page still says "n views".
So, what's the point in being picky and showing n+1 to me and the not updating it, thus being off by x?
So, first of all the counter controller should be as slim as possible, and what if you loaded it within an iframe, auto updating without AJAX?
How to refresh an iframe not using javascript?
That would keep the counter up-to-date, you may render it with PHP just once per page view, and then just statically serve the resulting HTML file.

How to set offline a User in the DB when it closes the browser?

i have a logout function that sets the User offline in my DB (mysql), but if it just closes the browser, in my DB the User is still online despite it's not , How can i manage this? How can i set the User Offline without press the logout botton? Cheers in advance !
Ps: Yes, i'm using SESSION
You can do it in following ways.
1) send the Ajax request to server every 5 seconds to update the current time.
2) and where you want to show offline just get records where current time is more than 5 seconds ago.
HI the only reliable way is to set an interval that calls the server and logs it in a database
var timeout = 15000; //milliseconds
setInterval( function(){
$.post('yoursite/keepalive' );
}, timeout );
Then you check the session on the server side you need a simple database table with the user id and a timestamp of the last time keepalive was called, then you just get the current time an there id ( from the session ) and save that. Then you can check if its been more then say like 20 seconds you will know they are gone ( should be updated every 15 sec ). Obviously you would need to have this interval on every page of your site to accurately track a user.
Things such as checking the session time, and unload are not accurate enough,
Unload is fired when any page is closed, so for example,
we have a user that has 2 pages open, they close one of them. the other page is already loaded so there is no traffic between client and server, and no way to know that page is still open
for Session time we have a similar problem, say someone is reading a long post on your page, They need to use the facilities and leave the page open. 30 minutes go by the come back and continue reading the post for another 10 minutes. now maybe the session has expired maybe it hasn't the fact remains they are still looking at your site, and you have no way to know it.
An interval will continue as long as the page is open and there are no javascript issues. A disadvantage of this is it will also keep their session updated ( you can get around this by sending the user id along with the ajax and not using the session, but that has other complications ) because you have that 15 second update you can check anytime if it has been more then 15 seconds. Say you want to display a list of online users to your other forum users, you just query for everyone with a current timestamp from that table, easy beazy.
As for the amount of time for the interval, you have to strike a balance between performance ( network traffic ) and how granular you need to know the information, if it's ok to only know if they logged off within the last minute then use that, if you can wait 5 minutes to know etc....
Really the Crux of the problem is how the server, and a client communicate. Right there is no two way communication like if your on the phone. It's more like a walkies talky where you have to say 10-4 and let go of the button for the other guy to talk. Essentially a client will make a request, that request is fulfilled by the server. that is the end of the communication and the state. Subsequent request state is maintained by using session so the next request uses that session to 'remember' the client. other then that there is no communication between client and server. There is no way to know they hung up the phone, for example, but to ask them if they are still there. ( this is an oversimplification because you cant send a request from the server to ask, more like they have to tell you they are not there, unless you use node.js or something like that ).
As #David has mentioned you could track this based on last activity, for that you would just need to know when the session was last updated. One of the easiest ways is to move the session into a database handler via http://php.net/manual/en/function.session-set-save-handler.php that way you can access when they were last active.
Using this vs ajax really depends on what you need to know, and how accurately. There is also the content of your page to weigh in. If you have a site that makes requests frequently it would be a better approach because you save on network traffic, for example. However, if you have long post someone could be reading for 20-30 minutes but want to know more frequent then that use ajax.
You can do it in many ways:
Launch an AJAX call on onbeforeunload javascript event. Prompting for a confirmation "Windows is closing, are you sure? YES/NO" should give you enough time to set the flag in the db, just be sure that if the user clicks "NO" you should unset your flag
Check session time... Add a var in your PHP_SESSION that is updated at every user event. If it becomes older than a preset threshold (i.e. 5 minutes), you can safely assume the user is gone
Example for onbeforeunload
function myConfirmation() {
return 'Are you sure you want to quit?';
}
window.onbeforeunload = myConfirmation;
You can try the javascript beforeunload event:
window.onbeforeunload = function() {
// Some AJAX request to logout.php or whatever script handles the logout
}
It will trigger when the user attempts to close the current window.
Watch out though, even if the user closes a single tab (your page), the event will be triggered, so if there are other tabs opened, so the browser will be, and you'll still get your users logged out.
Also, if several tabs of your website are opened, and you close one of them, you'll get your users logged out, which may not be what you want, so you'll probably have to find a way around to fix it.

Save only changed objects on server : Restful service + angularjs

I display a list of posts on my page with a like button that the user can toggle on or off.
In order to throttle the traffic with my server, I would like to:
send updates for all the posts where the like status has changed at once in the same request
send updates for the modified posts only
update the like status each N seconds, and on page exit only. Not each time a user toggles a like button.
Is this possible with angularjs?
I've written up an example that can be seen here:
http://plnkr.co/edit/imMGTJ75mKJZT7ispD9E?p=preview
I've spent some time on it with commenting, and providing useful information that gets displayed on the page itself when it runs. Change around the delays if you'd like it to run slower if the messages are moving too quickly.
From your question it looks like you want to save when a user makes any changes to a particular post. You proposed checking every x seconds for changes, but this isn't ideal (though it would be simple to implement with a setInterval). You also mentioned saving the changes on page exit, but it's impossible to guarantee that something happens on page exit (a user loosing power for example).
To avoid the above, I would fire the ajax call when the user clicks the "like" button, but throttle them after the first click & store their changes while the throttle timer is running and push all their changes at once after the timer ends.
Here is what my plunker code does in a nutshell:
User "likes" or "unlikes" a post and it will make an Ajax call to the server with the new information on the post. At this point, any new "likes" / "unlikes" gets thrown into a "queue" of posts that need to get updated.
When the first Ajax call is successful, the throttle timer starts. In the example I've provided it is 5 seconds. Any changes to a post ("likes", "unlikes") will be thrown in that same "queue".
After 5 seconds is up, it will check the "queue". If it's empty, no action is taken. If it has items in it (e.g. posts that have changed), then it will make a second ajax call and update the posts on the server.
My example won't mirror what you're working on exactly, but it's the concept that matters. You could modify the code so it doesn't throttle for such a long time, or have it only throttle after x number of ajax calls in a certain amount of time, etc.

Categories