[Request] Client Online Counter

Chuckie_

Active Member
Jun 22, 2019
138
71
You make a polling function that sends an ajax requests that queries the current online users every 30-60 seconds. I think Cosmic has it - you can look how it's done there. What CMS are you using?
 

Chuckie_

Active Member
Jun 22, 2019
138
71
Make a PHP page that will return the amount of online users.
PHP:
<?php
$connection = new mysqli("db_host", "db_user", "db_password", "db_name");

$sql = "SELECT COUNT(*) FROM users WHERE online='1'";

$result = $connection->query($sql);

echo $result;

$connection->close();

Save it as online.php or something in your pages folder, so that you can get the online count by going to the url.

Then add a script in your client.php that fetches the online amount every x seconds. In this example every 10 seconds (the fetchInterval variable).
JavaScript:
<script>
const fetchInterval = 30000 // Time between each fetch query 30000/1000 = 30 seconds.

let getOnline = () => {
    fetch('/online').then(res => {
        document.querySelector("#online-element").innerHTML(res);
    })
}

setInterval(getOnline, fetchInterval);
</script>

This assumes that you will be having some kind of HTML element with the id online-element, where it will output the current online amount. You can rip it off someone else's client page or design your own, I won't spoonfeed you that much.

Please note, this should be considered pseudo code, as I haven't done PHP and vanilla JS in ages.

Good luck :)
 

Users who are viewing this thread

Top