简体   繁体   中英

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

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..

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM