简体   繁体   English

放置 SweetAlert 后,表单未满足

[英]form doesn't submet after putting SweetAlert

I have a form, I want to show a sweet alert after the user submits it, but it's not working我有一个表单,我想在用户提交后显示一个甜蜜的警报,但它不起作用

<form action="rideHandler.php" method="POST" id="tripinfo">
//input
 <button id="ok"  type ="submit" class="subBtn" name="ok" >Offer my ride</button>
</form>

the script:剧本:

$('#ok').click(function(e) {
    e.preventDefault();
    swal({
  icon: "success",
  
}).then(function() {
    $('#tripinfo').submit();
});

    });

the PHP file : PHP文件:

if (isset($_POST['ok'])) {
//continue to enter database
header("Location: page2.php");
}

I know the issue is coming from the PHP because if (isset($_POST['ok'])) is returning false, how do i fix this?我知道问题来自 PHP,因为如果 (isset($_POST['ok'])) 返回 false,我该如何解决这个问题?

Since you prevent the default behavior of the submit button, it doesn't send it's name to the server when you submit the form programmatically (like it would do on it's default behavior).由于您阻止了提交按钮的默认行为,因此当您以编程方式提交表单时,它不会将其名称发送到服务器(就像它的默认行为一样)。

One way to fix it (via html ) is to give one of your inputs the name "ok".修复它的一种方法(通过html )是将您的输入之一命名为“ok”。

another way (via php ) is to change the isset to search/check another name (not the "ok" that doesn't send).另一种方法(通过php )是更改isset以搜索/检查另一个名称(不是不发送的“ok”)。

If you want to check what the server is getting when you submit the form just:如果您想在提交表单时检查服务器正在获取什么:

 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   print_r($_POST);  
 };

The reason for this behavior is when user clicked submit button, that button is added to the form's data to be submitted, however when javascript submits the form the form ignores all submit buttons, because none of them were clicked.这种行为的原因是当用户单击提交按钮时,该按钮被添加到要提交的表单数据中,但是当 javascript 提交表单时,表单会忽略所有提交按钮,因为它们都没有被单击。

So to fix that, you need click on submit button instead of submitting the form, but because you already listening for click event on submit button, you'll need identify if a user clicked it or it was done via javascript by checking event.isTrusted property:所以要解决这个问题,你需要点击提交按钮而不是提交表单,但是因为你已经在监听提交按钮上的点击事件,你需要通过检查event.isTrusted确定用户是点击了它还是通过 javascript 完成的财产:

 $('#ok').click(function(e) { // check if user clicked the button if not, do nothing and exit the function. if (!e.originalEvent.isTrusted) return; e.preventDefault(); swal({ icon: "success", }).then(function() { e.target.click(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/sweetalert"></script> <form action="rideHandler.php" method="POST" id="tripinfo"> //input <button id="ok" type="submit" class="subBtn" name="ok">Offer my ride</button> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM