0

I have a user status field (online/offline) in database. when user hit logout button at that time in database change online to offline. but if user directly close browser without hitting logout then how to update database.

JDG
  • 3
  • 5
  • 1
    [onbeforeunload](https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload)? See also [javascript detect browser close tab/close browser](http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser). – Antony Mar 29 '13 at 07:14
  • 1
    This might work. Create a cron job and check activity of user eg: last activity in db and if user hasn't had a update in x minutes change to offline. – Class Mar 29 '13 at 07:20
  • cant work. If page refresh also run onbeforeunload. Plz give me any other solution – JDG Mar 29 '13 at 10:08

1 Answers1

1

Unless you have a process which pings your servers at a regular interval, you can't.

Your logout button most likely sends a request back to your server. Upon receiving that request, the server runs/delegates logic to update the DB. If the user closes the browser without clicking the logout button, the server never gets this request.

@Antony gave a possible solution.

Another possible solution would be to send a message to your server at a given interval. The server should expect this call. If the server doesn't receive the message, then mark the user as being logged out. It has the downside of the logout timestamp being off by the interval. The logout time will not be exact. See this thread for more detail Ajax call with timer

Edit #1 In the link I mentioned above it mentioned how you can run javascript code at an interval.

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

In your case use this function to call your API.

Your API should record timestamps of when it last received a call from your javascript. Have a cron job, or another piece of logic to check when the recording for that particular user stops. The last timestamp would be the approximate time the user logged out.

It's a very involved process for simply tracking a user's logout behavior. You may want to consider if it's worth the trouble.

Community
  • 1
  • 1
rexposadas
  • 3,109
  • 3
  • 27
  • 49
  • Thanx bu I cant get solution. – JDG Mar 29 '13 at 10:12
  • @JD I'm not sure what you mean by your comment. Does that mean you don't understand what I wrote or you don't know how to implement the possible solutions? – rexposadas Mar 30 '13 at 05:48
  • @rexposadas... ya.. I don't know how to implement the possible solutions – JDG Mar 30 '13 at 08:41
  • @JD please see my edit. At a high level, this would be one possible solution. – rexposadas Mar 31 '13 at 03:19
  • @rexposadas.. But how i know or check the user session's status. I only set status "offline" which session status is destroy. – JDG Apr 26 '13 at 07:54