Executing a php script in javascript?

后端 未结 3 2080
南旧
南旧 2021-01-17 05:23

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

相关标签:
3条回答
  • 2021-01-17 05:56

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

    0 讨论(0)
  • 2021-01-17 06:03

    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'");         
    ?>
    
    0 讨论(0)
  • 2021-01-17 06:07

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

    0 讨论(0)
提交回复
热议问题