How to show online users using ajax

I want to show all users who are online in real time on my website. Not sure how to do this. It is not possible to add new users after logging in, but I will also need to remove users who are no longer logged in.

Any ideas how to do this? Should I check with jQuery that users are logged out and removed from the list, etc.?

+5
source share
2 answers

The problem is that people will move without logging out, their session will still exist for how long you will have a timeout set before their session data is collected (in fact, it may be much longer )

In order to get a truly accurate account of who has registered and visits the site, each client will send a "heartbeat" to the server every few seconds or minutes. at each heart rate trigger, you would like to expire any users who did not check within the allocated time interval.

The heartbeat signal is probably best composed of a username and a timestamp at a minimum, but may include any information you want to track.

, , , . , . , , , . 30 , .

(, , , ) , , SELECT * FROM table, .

:

, heartbeat .

//Client-side parent variable declaration (simulated namespacing)
var Client = Client || {};
Client.Pulse = null; //Holds a pointer to the heartbeat timer (id)
/* If you needed to cancel the heartbeat processes you could
 * pass this variable to clearTimeout(). Calling Client.Heartbeat()
 * again would start the cycle back up.
 */

//Initial event that will kick off the chain when the DOM is ready
$(document).ready(function(){
  Client.Heartbeat(); //Initial call to the Heartbeat function
});//ready

/// Sends the heartbeat signal and retrieves the currently active user list
Client.Heartbeat = function(){
  var sUsername = 'SomeUser';
  /* Note: If you have an active session running on the server it would not be 
   * necessary to send the username since you could pull it on the backend 
   * script which would be more tamper-proof anyway. I'm just giving an
   * example of sending data to the server using the jQuery.ajax method
   * If you were storing the username to be sent from the client; this wouldn't 
   * be a good place to do it anyway
   * 
   * Remove the "data : {...}" line below to exclude sending information to the server
   * The "type : 'post'" line would not be necessary either 
   */

  $.ajax({ //Send the signal and recieve the information about active users back
    url : '/lib/server/Heartbeat.php',
    type : 'post',
    dataType : 'json',
    data : {Username : sUsername },
    success : function(jActiveUsers,sStatus,jqXHR){ 
      /* This is the callback function of the request, jActiveUsers will be the 
       * json object with the information you choose to send back to it
       */
      Client.RenderActiveUsers(jActiveUsers); //Call the display function
      //Trigger the next delayed call to Client.Heartbeat
      Client.Pulse = setTimeout(function(){
        Client.Heartbeat();
      },30000); //30 second delay before next trigger
    }//success
  });//$.ajax
}//Heartbeat

/// Processes the results sent by the server and draws them to the UI
Client.RenderActiveUsers = function(jActiveUsers){
  /* This is where you would get a handle whatever element(s) on the page
   * will be displaying the information about currently active users
   * and filling it with the list of users how ever you would wish to display it.
   */
}//RenderActiveUsers

setTimeout(), , setInterval(), , , . setTimeout() ; , ( , ).

:

, Java , , , PHP; , . MySQL. PHP (ish)

. , , , ( , , , )

:

 ActiveUsers
 -----------------------------------------
 |   Field    |    Type     | NULL | Key |
 -----------------------------------------
 | Id         | int         |      | PRI |
 | Username   | varchar(xx) |      |     |
 | LastPulse  | datetime    |      |     |
 | FirstPulse | datetime    |      |     |
 -----------------------------------------

() , , PHP, Java Sessions, , , . PHP , , , (, , .)

, , , -, . , ....

, , , .

if($LoggedIn && ($Username != null)){ //Session information

, , .

,

SELECT `Id` FROM `ActiveUsers` WHERE `Username` = '{$Username}' LIMIT 1

, , , , Id,

UPDATE `ActiveUsers` SET `LastPulse` = NOW() WHERE `Id` = {$Id}

,

INSERT INTO `ActiveUsers` (`Username`,`LastPulse`,`FirstPulse`) VALUES ('{$Username}',NOW(),NOW()) 

, , , , (2 ).

DELETE FROM `ActiveUsers` WHERE `LastPulse` < (NOW() - INTERVAL 2 MINUTE)

ActiveUsers , , , , , ,

SELECT `Username`, UNIX_TIMESTAMP(`FirstPulse`) AS `FirstPulse` FROM `ActiveUsers` ORDER BY `FirstPulse` ASC

( PHP) , JSON json_encode() print() ed "application/json", jQuery . , Java , " , JSON " .

, . , .

100% - , . , .

( , Wall-O-Text)

+17

ajax- , . setInterval ajax. №. .

+2

All Articles