1

I've been crazy thinking about how to solve this problem updating mysql when browser is close. I have a login in my web application when users logs in and status=1(online) then status=0(offline) when they logout.

Is there any proper or best practice to handle this situation? Any solution would be appreciated. Thank you.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Rye
  • 179
  • 3
  • 17
  • You may use ajax call to update your database, Read more here : https://stackoverflow.com/questions/6162188/javascript-browsers-window-close-send-an-ajax-request-or-run-a-script-on-win – teeyo Nov 03 '17 at 09:35
  • You can use [mysql Triggers](https://dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html) – Hamza Abdaoui Nov 03 '17 at 09:35

2 Answers2

1

1- You can use unload or beforeunload events, which will be fired on tab/window/ close but you will never be sure, if its really reached the server.

2- You can use "Heartbeat" if you are able to use NodeJS on serverside and if a client does not send a heartbeat message, you can just update it for the client on the server side.

3- Another way would be, when the client is online or offline, you can add a new column (DateTime) to your table and update it on activities. if the date is older then (example 10Min), it means that users may be offline.

Vural
  • 8,666
  • 11
  • 40
  • 57
0

Capture the Window close event like this -

$(window).on("beforeunload", function() { 
    // YOUR CODE
})

Now in YOUR_CODE section, make an ajax request and update the user with status 0. That means if user closes the window without logging out, still you will be able to set the status 0.

Rudraksh Pathak
  • 888
  • 8
  • 20