尽管使用 Onsubmit 确认,HTML 表单仍然设置 PHP $_POST[]

HTML form still sets PHP $_POST[] despite using Onsubmit confirmation

HTML -

<form id="anID" method="post" onsubmit="confirm('Want to make this change?')" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
    <input type="text" name="amount">
    <input type="submit" name="add" value="Add Amount">
</form>

PHP -

if (isset($_POST['add'])) { Add amount to database }

我的问题是,尽管在 onsubmit 对话框出现时按 "Cancel",POST 表单仍然设置,并且 PHP 中的所有代码If() 声明还在提交,我不要这个。

有没有办法在 isset() 激活之前确认提交?

最好是不需要单独的 JS 函数的简单解决方案。

您需要 return 来自 confirm() 的响应以停止提交表单(如果它 returns false。返回 true 将允许要提交的表格):

onsubmit="return confirm('Want to make this change?')"

首先你没有关闭表单语句

最重要的是 - 您必须将 return 从对话框设置为表单。 这是正确的行:

<form id="anID" method="post" onsubmit="return  confirm('Want to make this change?')" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">