Removing data from the database if the user has closed the browser

Hello, how can I determine if the user has closed the browser and deleted something from db? I want to use it for online counting, because when the user closes the browser, he is still “online”.

+4
source share
3 answers

there is an event for this. if the user closes the actual tab, this function will work.

window.onbeforeunload = function () {
    //make an ajax call here and modify your db
}
+2
source

"onunload" vs "onbeforeunload" are the correct answers, but you must also send an AJAX call to the 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})
});

: , . nodejs, , . socket.io(library nodejs)

+1
$( window ).unload(function() {
  // call your ajax function for deleting database. 
});

You can use jquery unload. therefore, when the user tries to close the browser, the function will load.

-1
source

Source: https://habr.com/ru/post/1666560/


All Articles