简体   繁体   中英

AJAX function onBeforeUnload doesn't work

I am tracking the length of time an individual user is on my site. In order to achieve this I am logging the timestamp of when the user first loads the page and each time they click on a new page.

A brief summary:

Database table (time_on_site):

+-------+-----+-----------+----+
| start | end | unique_id | id |
+-------+-----+-----------+----+
  1. INSERT timestamp in start when session is created (just the once).
  2. UPDATE the timestamp in end each time the onbeforeunload event is fired.

This works fine for tracking the time they're on the site while browing pages, but when they leave the site (ie, browser is closed/exited), a problem is occuring and I don't know how to find it. Basically the end record just isn't getting updated with the timestamp. It's like the AJAX function is not getting called properly since the browser is closing. I have set async to false in the AJAX call, but that does not help.

Why is this function not working when the user closes the browser, but works all other times the onbeforeunload event fires?

Edit

Error was simply that there was no check for else if($_GET['when'] == "end") .

Here's my code:

index.php:

// If the session DOES NOT EXIST, make it and set it to TRUE.
if(!isset($_SESSION['new_visit']))
{
    $_SESSION['new_visit'] = true;
}

// If the session is TRUE, make it false.
if($_SESSION['new_visit'] == true)
{
    $this->db->store_visit();

    $_SESSION['unique_session_id'] = hash("sha512", uniqid("", true) . uniqid("", true) . uniqid("", true));

    $_SESSION['new_visit'] = false;
}

At the bottom of index.php:

<script type="text/javascript">

    if(window.addEventListener)
    {
        window.addEventListener("load",         function(){log_time("start");}, false);
        window.addEventListener("beforeunload", function(){log_time("end");  }, false);
    }

    function log_time(time)
    {
        var xmlhttp = "";
        var session = "<?php echo $_SESSION['unique_session_id']; ?>";

        // IE7+, Firefox, Chrome, Opera, Safari.
        if (window.XMLHttpRequest)
        {
            xmlhttp = new XMLHttpRequest();
        }
        // IE6, IE5.  
        else
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET", "/application/logtime.php?session=" + session + "&when=" + time, false);
        xmlhttp.send();
    }

</script>

logtime.php:

//session_start();

require "database.php";

$db = new Database();

$unique_id = $_GET['session']; //$_SESSION['unique_session_id'];
$time      = time();

if($_GET['when'] == "start")
{
    if($get_rows = $db->mysqli->query("SELECT 1 FROM time_on_site WHERE unique_id = '$unique_id'"))
    {
        $rows = $get_rows->num_rows;
    }

    // If rows were afffected, the unique ID has already been stored so we must UPDATE. This happens each time a page is refreshed.
    if($rows >= 1)
    {
        $db->mysqli->query("UPDATE time_on_site SET end = '$time' WHERE unique_id = '$unique_id'");
    }

    // Else if the rows affected were 0, we must INSERT a new record. This happens once per session (visit).
    else
    {
        $db->mysqli->query("INSERT INTO time_on_site(start, unique_id) VALUES('$time', '$unique_id')");
    }
}
if($_GET['when'] == "start")
{
    // ...
}

This conditional is missing an else branch, so if $_GET['when'] != "start" , nothing will happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM