Skip to content

Instantly share code, notes, and snippets.

@mtrpcic
Created September 20, 2014 02:27
Show Gist options
  • Save mtrpcic/2ed5da78eca239ffe47a to your computer and use it in GitHub Desktop.
Save mtrpcic/2ed5da78eca239ffe47a to your computer and use it in GitHub Desktop.
$(document).on("ready", function(){
window.LOAD_TIME = new Date();
var Poller = {
interval: 500,
poll_id: null,
start: function(callback){
this.poll_id = setInterval(callback, this.interval);
},
stop: function(){
clearInterval(this.poll_id);
this.poll_id = null;
}
};
Poll.start(function(){
$.get("poll.php", function(response){
if(response && response != ""){
var timestamp = new Date(response);
if(timestamp > window.LOAD_TIME){
window.location.reload();
}
}
});
});
});
<?php
// Configuration
define("PASSWORD", "lemonlime");
define("FILENAME", "update.txt");
// Should we update?
$update = isset($_GET["password"] && $_GET["password"] == PASSWORD);
if($update){
$timestamp = date('D M d Y H:i:s O');
file_put_contents(FILENAME, $timestamp);
echo "TIMESTAMP UPDATED TO: " . $timestamp;
} else {
echo file_get_contents(FILENAME);
}
?>

Setup

  1. Put poll.php somewhere on your server
  2. Include poll.js on your web page, anywhere after jQuery. Update the poll interval if you want, and update the URL on line 18 to point to your poll.php file

Viewers

Viewers will start polling every 500ms (the default I set in poll.js) for updates. If an update is found, the page will refresh.

Admin

Admins can make a request to poll.js from directly in their browser (weebcrew.com/poll.php, if that was the path). They need to pass a GET parameter that matches the password defined in the file. If it matches, it will trigger an update to the timestamp file (filename defined in poll.php, and can be changed to anything). A request with the password would look like http://weebcrew.com/poll.php?password=YOUR_PASS_HERE. When users of the site start polling, they'll get this file and compare it to their LOAD_TIME. If the file has an updated time from after they loaded the page, it will trigger a refresh.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment