将Java Script var传递给PHP $ var

时间:2016-11-01 15:25:03

标签: javascript php ajax html5

我正在index.php创建一个以登录页面开头的简单聊天室 有一个表单将密码变量发送到PHP_SELF,PHP获取变量,如果密码正确,则用户成功进入聊天室。

有一个消息输入就像表单一样 但我不能再使用表单了,因为如果表单发送消息输入,页面重新加载,用户首先进入(登录页面)。
所以我想发送我的variable而不重新加载页面。

我已尝试使用$var = "document.getElementById('input).innerHTML",但这不会返回任何值!

我尝试过使用AJAX。聊天室为index.php,我的助理页面为post.php index.php AJAX的工作原理如下:

            var message = 'document.getElementById('input).innerHTML';
            $.ajax({
                type: "POST",
                url: 'post.php',
                data: message,
                success: function(data)
                {
                    alert("200");

                }
            });
        });

post.php收到变量,然后再次向index.php发送变量。 post.php php:

if(isset($_POST['message'])) $mymsg= $_POST['message'];

post.php AJAX:

            var message = '<?php echo $mymsg ?>';
            $.ajax({
                type: "POST",
                url: 'index.php',
                data: message,
                success: function(data)
                {
                    alert("200");

                }
            });
        });

我的意思是我希望当用户成功登录并写下他的消息并点击提交时,这些都会发生。 index.php接收变量并插入数据库表。 但这对我不起作用。 请说什么不对,或者我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果不重新加载浏览器,您可以使用javascript

将其放在<body>代码

之前
<script>
$(document).ready(function(){
    $("#varbtn").click(function(){
        var var1 = $("#var").val();

            $.ajax({
                method: "POST",
                url: "post.php",
                data: {
                    var:var1
                    },
                success: function(data){
                //#success will be the id of the div you want to put the response of the php file
                    $("#success").html(data);
                }
            });
    });
}); 
</script>

在表单中,您无需创建<form>标记

<input type="text id="var" />
<button id="varbtn"> Submit</button>

<!--this div will be the result of the post.php file-->
<div id="success"></div>
post.php中的

//will check if the person will direct visit that post.php, this is not secured enough but hes doing his job actually 
<?php 
if(isset($_SERVER['HTTP_REFERER'])){
    if(!isset($_POST['var'])){
        //your codes here
    }
}
?>
相关问题