4

Hello how can i detect if user closed browser and delete something from db? I want to use it for online count because when user close browser he is still "online".

Jakub Staněk
  • 1,023
  • 1
  • 10
  • 11
  • 1
    You should look into [`.unload()`](https://api.jquery.com/unload/) with the [`Jquery`](http://jquery.com/) library. Then, when the page is *unloaded* you send a [`Ajax`](http://api.jquery.com/jQuery.ajax/) request. **Note**: SO is **not** a *free* coding service! – Nytrix Jan 11 '17 at 22:50
  • [this](http://stackoverflow.com/questions/11104205/php-how-to-detect-is-a-session-id-is-dead-or-alive) may be helpful? – haelmic Jan 12 '17 at 06:23

3 Answers3

3

there is an event for this. if a user closes the actual tab this function will run.

window.onbeforeunload = function () {
    //make an ajax call here and modify your db
}
lacexd
  • 903
  • 1
  • 7
  • 22
1

"onunload" vs "onbeforeunload" events is correct answers, but additionally you must send an AJAX call to a PHP file.

window.onbeforeunload = function () {
    jQuery.ajax({url:"http://localhost:8888/do_somethink_in_db.php?", async:false});
}

OR

$( window ).unload(function() {
  jQuery.ajax({url:"http://localhost:8888/do_somethink_in_db.php?", async:false})
});

Note: But when power is off in user pc this event cannot work. But if you use nodejs server you can detect user is ofline or online. Because with socket.io (library nodejs) server check heartbeat

Ramin Darvishov
  • 1,043
  • 1
  • 15
  • 30
-1
$( window ).unload(function() {
  // call your ajax function for deleting database. 
});

You can use jquery unload. so when user try to close the browser then the function will load.