nn3112337
nn3112337

Reputation: 599

Im trying to run a .php script if a user closes his browser

So im making a game lobby atm and want to run a .php script if a user closes or refreshes his browser.
My problem is, the .unload doesn't even fire, but it should, I basicly used the exact same thing in the wiki. What did I do wrong?

My index:

<script type="text/javascript">

jQuery(document).ready(function ($) {
    $(window).on('beforeunload', function() {
        return "Do you really want to leave this lobby?";
    });

    $(window).unload(function() {
        alert("wat");
        xmlhttp.open("POST","test_ajax.php",true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("session=test");
    });
});

</script>

My test_ajax.php:

<?php

$db_name = "test";
$db_username = "root";
$db_password = "";
$db_host = "localhost";

mysql_connect($db_host, $db_username, $db_password) or die ("No connection possible!");
mysql_select_db($db_name) or die ("No database found!");

$v = "Testaccount";
$sql = mysql_query("UPDATE users SET Avatar=1 WHERE Username='$v'");

?>

Upvotes: 0

Views: 91

Answers (1)

Dmitry
Dmitry

Reputation: 7246

IMO the only solution is to send some heartbeat signal every N seconds. If the heartbeat stops - user has closed the browser. There is no reliable JS event for browser closing. You can show a message with onbeforeunload event but you don't have enough time to send an ajax from that callback. If this callback does not return in a 1ms or so the page will just close. It is made this way because if a user enters a malicious page and wants to close it, the page won't be able to run some infinite loop in onbeforeunload callback to prevent the user from closing the page.

Upvotes: 1

Related Questions