Fr0z3n
Fr0z3n

Reputation: 1576

Check users status

I want to make a user status system and i was thinking to have in my database a datetime field called last_active and update that field automatically with ajax with current time.

Then i check minutes between last_active and current time.. to tell if the user is online, inactive and offline..

Is this a good technique? and what happens if the user for example has the site open but is doing something else?

Is there a way to fire ajax request only if the user is viewing the page?

Upvotes: 1

Views: 264

Answers (2)

Bhavesh G
Bhavesh G

Reputation: 3028

Your current method is a good technique to do, and the way to go,

you can check with focusin and focusout function with jquery to check if user is currently active on document or not,

$(document).ready(function(){
    $([window, document]).focusin(function(){
      // start the ajax requests
    }).focusout(function(){
      // stop the ajax requests
    });
});

you should take variable that will set to true in focusin function and, will set to false in focusout function. now the continues ajax request function will fire only if the variable is set to true.

Upvotes: 2

Emil Vikström
Emil Vikström

Reputation: 91963

This is a very good way to check for activity. You can fire Ajax requests when the page is in focus only. I would consider using the mousemove event or similar, but also the blur/focus events can prove useful.

When the mousemove event is fired, set a variable to true and check thet variable before doing your Ajax request. Don't forget to reset it to false between each Ajax call.

Upvotes: 1

Related Questions