2

I have a table like this:

// last_seen
+----+---------+--------------+
| id | id_user |     time     |
+----+---------+--------------+
| 1  | 545     | 1339412843   |
| 2  | 653     | 1339422601   |
| 3  | 813     | 1339412612   |
| 4  | 1030    | 1339717631   |
+----+---------+--------------+

Every user has a row in table above. That row contains a unix_time which declares the time of last seen for each user.

Also I have this PHP script (named update_last_seen.php) which updates last seen for each user per every request:

// user is logged
if( isset($_SESSION["LoginValidation"]) && $_SESSION["LoginValidation"] == 1 ) {

   // it is ajax request
   if( !empty($_SERVER["HTTP_X_REQUESTED_WITH"]) &&
       strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest" ) {

        $db
        ->prepare("UPDATE last_seen SET time = ? WHERE id_user = ?")
        ->execute(array(time(), $_SESSION['id']));

   } -- ajax
} -- logged

Currently I run script above first of all into index.php. I mean each page updates last_seen table before loading. So the request does get slowed down by the update.

Now I'd make that an AJAX push request when the page finished loading. Is there any JS event to detect page is loaded completely?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111

3 Answers3

2

You can use the vanilla JS event DOMContentLoaded and make an ajax call to the file.

Or you could use jQuery .ready and $.ajax

$(document).ready(function() {

    $.ajax({
        url: '/last_seen.php',
        type: 'POST',
        dataType: "json",
        data: { id: '3' }
    }).done(function(data){

    });

});
aifrim
  • 555
  • 9
  • 20
0

As far as i know in vanilla JS you just have to call DOMContentLoaded.

document.addEventListener("DOMContentLoaded", function(event) {
   //insert code here
});
Cth103
  • 63
  • 5
-2

You can use the vanilla JS event DOMContentLoaded and make an ajax call to the file.
Put ajax functionality in the

$(document).ready(function() {
    //put your code here
}); 
Kuldeep
  • 202
  • 3
  • 8