I\'m trying to run a quick php script when users leave my website, and also pass a variable from my javascript to php but i\'m not quite sure how to include the php file and
You need to make an AJAX call to the PHP script. Your javascript code will just make a background request to the php script which will execute those MySQL statements. Google up AJAX. Recommended: Learn jQuery and use ajax using $.get()
or $.post()
Try an ajax request. Depending on your php script you will need $.post
or $.get
jQuery:
<script language="javascript" type="text/javascript">
var username = null;
function GetUsername(usernameff){
username = usernameff;
}
window.onbeforeunload = function(){
if (username != null){
$.post('scripts/RemoveUserOnDisconnect.php', {username: username}, function(){
//successful ajax request
}).error(function(){
alert('error... ohh no!');
});
}
}
</script>
EDIT:
Your php script should reference the $_POST
array if you use my code above.
<?php
$username = $_POST['username'];
mysql_connect("mysql.mysql.com", "username", "password");
mysql_select_db("my_db");
mysql_query("DELETE FROM my_table WHERE username = '$username'");
?>
Make an ajax call to scripts/RemoveUserOnDisconnect.php?username=username. You cannot include PHP with Javascript, Javascript executes on the browser, PHP executes on the server..