'Sweet Alert Form Submit Confirmation Doesn't Submit the Form
I'm using Sweet Alert to confirm the intent to delete records with the code below. I get the Sweet Alert Pop up, click OK...but the form never submits. I get the alert ('ok) (commented out in the code) but form.submit() does nothing. I've looked online for a solution but I mostly find form.submit() as the answer. Is there a way to get this working?
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<form method="post" action="" onsubmit="return submitForm(this);">
<input type="hidden" name="delete_data" value="10">
<input type="submit" name="submit-survey" id="submit" value="Clear Data">
</form>
<script>
function submitForm(form) {
new swal({
title: "Are you sure?",
text: "This will clear the data",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function (isOkay) {
if (isOkay) {
//alert('ok')
//return true;
form.submit();
}
});
return false;
}
</script>
Solution 1:[1]
Here is the only way I've found that works..and it requires two forms since it appears you can't do this with one form.
$(function(){
$("#from1").submit(function(e){
event.preventDefault();
let flag = $('#from1').attr('data-flag');
if(flag == 0){
Swal.fire({
title: 'Are you sure?',
text: "Do you want to clear out the submissions?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
closeOnConfirm: false,
closeOnCancel: false
}).then((result) => {
if (result.isConfirmed) {
$('#from1').attr('data-flag', '1');
$('#from2').submit();
} else {
Swal.fire("Cancelled", "Submission clearance cancelled", "error");
}
})
}
});
and then the two forms
<form id="from2" action="" method="POST">
<input type="hidden" name="clear_subs">
</form>
<form id="from1" data-flag="0" action="" method="POST">
Clear Submissions <input type="submit" id="checkbox" >
</form>
Solution 2:[2]
I think the problem is you've got a onsubmit="submitForm(this);" action, but then you're later calling form.submit() so it probably just repeats that same action every time. Checking the console with those console.log lines should confirm this by clicking the "Yes I'm sure!" button multiple times.
Instead of mixing the two, I'd recommend triggering something on the button's click to make the swal pop up, then if the result is confirmed call form.submit() from there.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allen |
| Solution 2 | Scott Salyer |
