Search code examples
phpjavascriptmysqlvariablesonbeforeunload

Executing a php script in javascript?


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

Solution

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