javascript - 如何在运行时将文本框值传递给 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
}
}
}
}
?>
解决方案
您需要在提交之前调用该函数。我添加了一个隐藏价值的警报。
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>
推荐阅读
- ruby-on-rails-5 - Capybara:无法找到 collection_select 和 text_field_tag 的 css
- javascript - 动态加载内容中的堆叠链接
- python - 通过 jupyter notebook 从 json 中的 csv 文件中获取值
- c# - 无法调用我的自定义剃须刀页面 (HTTP 404)
- c# - 为什么这个存储过程总是返回 1 进行删除操作?
- android-studio - 在 build.gradle 中实现 MaterialProgressBar 时 Appcompat 依赖项出错
- python - 有没有办法在 PRINT 语句的 FOR 循环 INSIDE 中编写?
- javascript - 如何仅在需要时才处理 ajax 请求,而不是每秒钟
- javascript - XMLHttpRequest.prototype.open 不会拦截 chrome-dev-tools 上显示的所有 HTTP 请求
- object - 适用于 python 3.7 的 Dlib whl