How do I log the user’s logout when he closes the browser or a tab of it?

Asked

Viewed 64 times

0

I am creating a web application and need to log user login and logout in a database table.

I did everything right, is logging in (when user logs in) and logout (when user closes system on button).

However, when the user closes a browser tab or the entire browser, logging is not done.

I tried a solution that I saw here in Stack, using Unload,.

I tried this code below:

$(document).ready(function() {
  $(window).unload(function() {


    $.ajax({
      url: "../banco/validador-de-login/logout.php",
      type: "POST",



    }).done(function(data) {



    }).fail(function() {


    }).always(function() {


    });


  });


});

  • You want this for rateability purposes or to ensure login when user comes back another day. because maybe it fits the use of global $_SESSION, instead of the usp of the bank in this way.

  • It’s just to have a record of when the user logged in and dropped out of the system.

1 answer

1


Dude, I got a solution (with a friend) that can be useful for many people who want to do something similar.

I used the window.onbeforeunload = Function(){} that performs the function when we close the browser.

Also, instead of using ajax, etc... I used $.get to call the log file.

The JS code looks like this:

window.onbeforeunload = function() {
  $.get("../banco/validador-de-login/logout.php", function(data) {
    return false;
  });
}

Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.