Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  158] [ 4]  / answers: 1 / hits: 24201  / 14 Years ago, tue, march 8, 2011, 12:00:00

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 pass it a var. But it's not actually running the php script. any ideas?



(the javascript gets the username from an external activity function, and i know that works i tested the var on an alert and its there.)



My JavaScript:



<script language=javascript type=text/javascript>

var username = null;

function GetUsername(usernameff)
{
username = usernameff;
}

window.onbeforeunload = function ()
{

if (username != null)
{

<?php include(scripts/RemoveUserOnDisconnect.php?username=username);?>
}

}


</script>


My RemoveUserOnDisconnect.php File:



<?php
mysql_connect(mysql.mysql.com, username, password);
mysql_select_db(my_db);
mysql_query(DELETE FROM my_table WHERE username = '$username');
?>

More From » php

 Answers
95

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');
?>

[#93384] Sunday, March 6, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;