Stack Stack - 5 months ago 9
PHP Question

How to run a query when the page is finished loading?

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?

Answer

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
}); 
Comments