i need to perform a MySQL query on database when a user closes his browser.i am developing a application where when a user logs in a database field lo-gin_status is set to 1 and when a user logs out his lo-gin_status is set to 0.but what should i do if a user logs in but does not log-outs he just closes his browser.
-
There is no way to make something like that for all situations. What you cold do is look at the [unload](http://api.jquery.com/unload/) event. But what if the browser crashes? Also, there are tons of questions out there that are either exactly the same as yours or very similar. – AmazingDreams Aug 03 '13 at 11:13
5 Answers
There is no way to reliably detect when the browser closes. Therefore, you cannot reliably manipulate the database when the browser closes. Therefore, you need some workaround for situations where you did not detect that the browser closes. Make that workaround the preferred method of doing whatever you intended to do when the browser closes and drop the requirement that you need to do something when the browser closes.

- 31,254
- 3
- 43
- 68
Try this
$(window).unload( function () { alert("AJAX function to do the required job"); } );

- 632
- 4
- 13
You could use an event like onunload
to send an event to your server, but you cannot be certain that this event will always be sent. I personally think it would be better to keep track of the last moment the user was active, and decide whether he is online or not based on that last active timestamp. It depends on your site how long this maximum timeout should be.

- 5,065
- 6
- 29
- 46
Try this way if you have really in trouble!
Add a column to user table like:
`live_last_update` TIMESTAMP NULL DEFAULT NULL
Update the field to current timestamp
in your app every (e.g. 5 minutes)
for logged in user. If user logged out manually set to null
.
It indicates that the user is online or not.
Use cron job
script, having the ability to schedule tasks to run in the background!
Because of you do not have access to sessions in cron job (Why?), write your script that check live_last_update
fields in all of user records where the field not updated in last 5 minutes
. So you know which users are not logged out. And be able to set null
if needed.
Set cron job
to execute special times.
Here is a good tutorial how to use cron jobs:
http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/

- 1
- 1

- 7,159
- 5
- 42
- 51
Why not have an ajax request every x seconds. If you have not heard from the browser in 3x seconds have a crown job clean up ?
Make sure you have heard back from the ajax call at least once other wise you will log people out who have JavaScript disabled

- 18,275
- 8
- 32
- 65