AJAX Real Time Online Visitors Tutorial
I tryed in the previous tutorial to make something easy to understand, and we'll try to see in this tutorial how we can play with the previous code to make an AJAX Real Time Online Visitors. The idea of the script is simple, the javascript request a remote script to get the number of online visitors and update it every minutes or two. So while visiting a page you can see the number of visitors changing in real time.

The PHP Script
There is many techniques to track online visitors with PHP, in this example I used the most simple one. The script check the sessions online and then consider the recent ones in an interval of about 3 minutes. This gives more realistic information, because visitors idle for a long period are considered not online, and in the same time we don't have to create complex script and store informations in database ... etc.
// idle time in minutes
define("MAX_IDLE_TIME", 3);
function who(){
$path = session_save_path();
if (trim($path)=="") {
return FALSE;
}
$d = dir( $path); $i = 0;
while (false !== ($entry = $d->read())) {
if ($entry!="." and $entry!="..") {
if (time()- filemtime($path."/$entry") < MAX_IDLE_TIME * 60 ) {
$i++;
}
}
}
$d->close();
return $i;
}
AJAX code
The javascript didn't change a lot, we just have less code. What we need in this case is just getting the data and display it, nothing to parse or to change. Timer have been set to update the counter every minute.
var RequestObject = false; // XMLHttpRequest Object
var Backend = 'http://www.phpmagazine.net/demo/ajaxonline/check.php'; // Counter url
window.setInterval("update_timer()", 60000); // update the data every 1 min
The main AJAXRequest and the ReqChange function in our case will be
/*
* Main AJAX online Visitor counter request
*/
function AJAXRequest() {
// change the message to Checking online ...
document.getElementById("online").innerHTML = "Checking online ...";
// Prepare the request
RequestObject.open("GET", Backend , true);
// Set the onreadystatechange function
RequestObject.onreadystatechange = ReqChange;
// Send
RequestObject.send(null);
}
/*
* onreadystatechange function
*/
function ReqChange() {
// If data received correctly
if (RequestObject.readyState==4) {
// if data is valid
if (RequestObject.responseText.indexOf('invalid') == -1)
{
// getting the response
var msgs = RequestObject.responseText.split('|');
// Tell the reader the everything is done
document.getElementById("online").innerHTML = msgs[0]+" visitors online";
}
else {
// Tell the reader that there was error requesting data
document.getElementById("online").innerHTML = "Error Requesting data";
}
}
}
In addition to this script I have used a div "online" that you can put anywhere in your page
AJAX online visitors
This is another way to use AJAX with PHP to retrieve information about online visitors, you can test the AJAX Online visitor script online, the PHP Script you can get it from here.











AJAX Magazine's RSS