简体   繁体   中英

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 :

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?

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".

another way (via php ) is to change the isset to search/check another name (not the "ok" that doesn't send).

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.

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:

 $('#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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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