首页 > 解决方案 > 如何在运行时将文本框值传递给 php?

问题描述

当用户将记录保存到数据库时,我检查了保存数据的记录。如果该记录已存在于数据库中,请使用消息框询问用户是否覆盖或取消。我想让用户响应 OK 或 Cancel。

首先,我在运行时从 php 调用 js 函数。JS 函数显示确认消息并将返回值传递给隐藏文本框。这部分工作正常。

但是,我无法将文本框值传递给 php 变量。

<script>

function confirmOverwrite() {
        var overwriterec = "";
        if(confirm("Do you want to overwrite the record? Click on OK to overwrite.Click Cancel to skip."))
            overwriterec="ok";
        }
        else
        {
            overwriterec="cancel";
        }
        document.getElementById("hiddenVal").value = overwriterec;
}
</script>
<form action="#" method="post">
    <div>
      <button  type="submit" name="Save"> Save data</button>
	    <input type="text" style="display:none" id="hiddenVal" name="overwrite" />
    </div>
</form>

<?php
if(isset($_POST["Save"])){
$Sql = "SELECT * FROM maintable WHERE userid='$userid'";
$result = mysqli_query($db, $Sql);
                                  
if (mysqli_num_rows($result)>0)
{
   while($row = mysqli_fetch_assoc($result)) 
   {
   
      echo '<script type="text/javascript">',
           'confirmOverwrite();',
           '</script>';           //can call the function and pass the OK or Cancel value to hidden text box.

        if((isset($_POST['overwrite'])) && !empty($_POST['overwrite']))
        {
          $Confirmation = $_POST['overwrite']; //I can't pass the hidden text box value to php variable.
           echo $Confirmation;
         }

         if ($Confirmation == "ok")
         {
           // update the record
         }
   }
  }

}
?>

标签: javascriptphp

解决方案


您需要在提交之前调用该函数。我添加了一个隐藏价值的警报。

if(isset($_POST["Save"])){
  if((isset($_POST['overwrite'])) && !empty($_POST['overwrite']))
  {
    $Confirmation = $_POST['overwrite']; //I can't pass the hidden text box value to php variable.
    echo $Confirmation
  }
}

function confirmOverwrite() {
    var overwriterec = "";
    if (confirm('Do you want to overwrite the record? Click on OK to overwrite.Click Cancel to skip.')) {
        overwriterec="ok";
    } else {
        overwriterec="cancel";
    }
    document.getElementById('hiddenVal').value = overwriterec;
    alert(document.getElementById('hiddenVal').value);
}
<form action="#" method="post" onsubmit="confirmOverwrite()">
    <div>
      <input type="hidden" id="hiddenVal" name="overwrite" />
      <button  type="submit" name="Save"> Save data</button>
    </div>
</form>


推荐阅读