Hi I'm trying to delete a row in a mysql database when the user leaves a page on my website but it's not working for some reason. I know the onbeforeunload works because if i delete everything in there and just put alert("test"); the alert shows. Can this not be done? My code is below thank you for any help
Javascript
<script type="text/javascript">
window.onbeforeunload = function(){
var id = document.reset.id.value;
$.ajax({
url: "Resetter.php",
type: "GET",
data: {'id':id},
success: function (response) {
alert(response);
}
});
}
</script>
PHP
<?PHP
$id = $_GET['id'];
$link = mysql_connect('localhost', 'root', 'root');
mysql_select_db("Colleges");
$delete = mysql_query("DELETE FROM `Table` WHERE `ID`='" . $id . "'");
mysql_close();
die();
?>
Since you're closing the page you're closing the connection to the server and therefore it won't wait for you Ajax call to finish. This isn't how onbeforeunload
works. It's client-side only. Also note, that onbeforeunload
can be a little finicky in my experience and doesn't account for every way a user can move away from your page.
To accomplish what you want, you'd have to set up some sort of long polling. Here's an example using PHP on the server-side: http://blog.perplexedlabs.com/2009/05/04/php-jquery-ajax-javascript-long-polling/
You could also use something like Node.js to listen for connections and disconnections from the page.