Executing a php script in javascript?

谁都会走 提交于 2019-12-19 11:55:30

问题


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

回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/5227132/executing-a-php-script-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!