如何在php中使用javascript中的变量?

如何在php中使用javascript中的变量?,javascript,php,html,Javascript,Php,Html,我现在脑子都快冻僵了。。 我在这段JavaScript代码中有一个变量 <script type="text/javascript"> $('#menuNameEdit').val(reservationId); </script> 你不能。这是不可能的。如果JS开始工作,那么PHP已经完成了 实现这一点的唯一方法是通过AJAX,尽管它极易受到攻击: $.ajax({ type: "POST", url: "your_php_script.p

我现在脑子都快冻僵了。。 我在这段JavaScript代码中有一个变量

<script type="text/javascript">

    $('#menuNameEdit').val(reservationId);

</script>

你不能。这是不可能的。如果JS开始工作,那么PHP已经完成了

实现这一点的唯一方法是通过AJAX,尽管它极易受到攻击:

$.ajax({
    type: "POST",
    url: "your_php_script.php",
    data: {var: your_variable},
    success: function() {
        console.log("ajax successful!");
    }
});
没有jQuery:

var request = new XMLHttpRequest();
request.open('POST', 'your_php_script.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(your_variable);
这需要在您的_php_script.php中:

$jsVariable = $_POST['var'];

这是非常容易受到攻击的,但是-始终通过用户可以修改的filter_var或htmlspecialchars对输入进行清理

如果您的表单已提交,您可以访问以下代码:

PHP

HTML

index.php


不能将客户端变量用于服务器端。为此,您必须首先使用ajax将其发送到服务器。当您输入的表单被提交时,您可以使用$\u REQUEST['reservationId']访问PHP中的值。
$jsVariable = $_POST['var'];
if(isset($_POST['reservationId'])){    
echo $_POST['reservationId'];    
}
<form method="" action="" id="form-id">
<input id="menuNameEdit" name="reservationId" type="text" class="form-control" disabled>
<input name="submit" type="submit" class="form-control">    
</form>
var menuNameEdit = $('#menuNameEdit').val();

 $.ajax({
        type: "POST",
        url: "index.php",
        data: {menuNameEdit : menuNameEdit },
        success: function() {
            console.log("Success!");
        }
    });
echo $_POST['menuNameEdit'];
<?php
if (isset($_POST['submit'])) {
     $reservationId = $_POST['reservationId'];
     $reservationId2= $_POST['reservationId2'];

//comparison

}
?>   
 <form class='addcategory' method="post"    enctype="application/x-www-form-urlencoded">

       <input id="menuNameEdit" name="reservationId" type="text" 
   class="form-control" disabled>

<input id="another" name="reservationId2" type="text" 
   class="form-control"  >
<input name="submit" type="submit" value="submit">

</form>