Javascript form submit doesn't submit properly - javascript

I have this very simple form using Sweet Alert and for some reason can't get it to work. When I click on the link it triggers the alert and when the alert is confirmed it reloads the page because it submits the form.
But for some reason when $_POST['delete_alert'] is undefined.
My code to trigger the alert:
<a id="sa-warning">Delete</a>
My form:
<form id="form" action="index.php" method="POST">
<button type="submit" name="delete_alert" value="delete">Delete</button>
</form>
And my Javascript:
$('#sa-warning').click(function() {
swal({
title: "Are you sure?",
text: "You will not be able to recover this alert.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function() {
document.forms["form"].submit();
});
});
I'm testing wheter the form has been submitted properly using this PHP code which is located on index.php:
<?php
if(isset($_POST['delete_alert'])) {
echo "form is submitted correctly";
} else {
echo "something is wrong";
}
?>

I think the problem is in document.forms["form"].submit();
HTML forms send the submit name=value only if button is clicked.
In this case it is not.
So i think you should use click instead of submit, but in your case it wont work, because the click will be catched by your javascript function.
So this is why the best solution si to use input

maybe is work : http://rachmanzz.github.io/AlertlightJS
$('#sa-warning').click(function(){
alertlightJS.$swalPost({ // $swalGet for GET Method
title : "Are you sure?",
text : "You will not be able to recover this alert.",
type : "warning",
confirmText:"Yes, delete it!",
cancelText:"No!"
},{
url : "index.php",
input : {
delete_alert:'delete'
}
},function(isConfirm,data,swal){
if(isConfirm){
swal(['receive',data['data']]);
}else{
swal(['cancel','thanks']);
}
});
});

Just a slight change in my form was needed. The submit button is not clicked when the form is submitted via Javascript. Thus the value of 'delete_alert' is never set.
Removing the submit button and adding an input field resolved the problem.
The correct form:
<form id="form" action="index.php" method="POST">
<input type="hidden" name="delete_alert' value="delete" />
</form>
Thanks to Barmar for pointing this out.

Related

Delete form wont submit

Im getting this error when im trying to submit my form
"TypeError: Cannot read property 'submit' of undefined"
My js file
function validateForm() {
event.preventDefault(); // prevent form submit
var form = document.forms["myForm"]; // storing the form
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this.",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
form.submit();
}
});
}
how i call the function
<button type="submit" class="btn btn-danger btn-sm " onclick="validateForm()">Delete</button>
its my first time posting something and am fairly new at coding, it somehow broke and i dont know what im doing
Edit:: how do i point it to this form or any other form if i choose to do so
<form action="{{ route('admin.users.destroy', $user->id)}}" method="POST" class="float-left">
#csrf
{{method_field('DELETE')}}
<button type="submit" class="btn btn-danger btn-sm " onclick="validateForm()">Delete</button>
</form>
add an attribute id on your tag form, and the you can have your form with
document.getElementById("demo");
Found it thanks for the help Nick, it was missing an id

Form is not submiting after the sweet alert confirmation

I'm having a table which contains some rows of data and I have delete button for each row.
My form is not submiting if I implement sweetalert2 with my code, what I need is, I need to delete my row only after sweet alert confirmation button.
Here is my Code;
<tbody>
<?php foreach ($category_details as $category_detail): ?>
<tr>
<td>...</td> <!-- etc -->
<form method="post">
<td>
<input type="hidden" name="delete-id" value="<?php echo $category_detail['id']; ?>">
<button type="submit" name="single-cdelete" class="swa-confirm btn btn-trash-alt">
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
<?php endforeach ?>
</tbody>
</form>
if(isset($_POST['single-cdelete'])){
$delete_id = $_POST['delete-id'];
$delete_image = $_POST['delete-image'];
category_delete($delete_id, $delete_image);
}
function category_delete($delete_id, $delete_image){
global $db;
if(mysqli_query($db, "DELETE FROM categories WHERE id =$delete_id")){
unlink('../assets/images/categories/'.$delete_image);
$_SESSION['success'] = "Category has been deleted successfully";
}else{
$_SESSION['success'] ="Something went wrong, Try again";
}
}
My SweetAlert Code:
<script>
$(".swa-confirm").on("click", function(e) {
e.preventDefault();
Swal.fire({
title: "Are you Sure ?",
text:"You want to Delete the selected Category",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#cc3f44",
confirmButtonText: "Delete",
closeOnConfirm: true,
html: false
}, function( confirmed ) {
if( confirmed ){
$('.swa-confirm').submit();
}
});
});
</script>
as the comment from #Tangoabc Delta you just can use .submit() event on a form, so :
first, give your form an id :
<form method="post" id="swaForm">
then use the script like this :
<script>
$(".swa-confirm").on("click", function(e) {
e.preventDefault();
Swal.fire({
title: "Are you Sure ?",
text:"You want to Delete the selected Category",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#cc3f44",
confirmButtonText: "Delete",
closeOnConfirm: true,
html: false
}).then(function() {
$('#swaForm').submit();
})
});
</script>
As it's evident from your code, you've used jQuery to perform a form submission.
As per the documentation, https://api.jquery.com/submit/, the method .submit() can only be used on a form.
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements..
Forms can be submitted either by clicking an explicit , , or , or by
pressing Enter when certain form elements have focus...
It can be seen that you're also relying on some other functionality Swal.fire(..) because of which, you had to do an event.preventDefault(), otherwise, the form would have submitted itself without hassle. But it's understandable that you will need this part of functionality.
So, to solve your problem, you need to add some kind of identifier to your form e.g. a class or an id. So, instead of doing this:
<form method="post">
..do, something like
<form method="post" id="myform">
..and in the code snippet, use this identifier to call submit():
update: Also, notice that sweetalert2 supports a promise, and therefore, will recommend using a then-able promise and use a catch block to track any errors.
$(".swa-confirm").on("click", function(e) {
e.preventDefault();
Swal.fire({
...
}).then((confirmed) => {
if (confirmed) {
$('#myform').submit(); // << here
}
})
.catch((error) => {
console.log(error)
});
});

jQuery prompt before submitting a form, PHP distinguishing which button was used

Good morning everyone.
I have problem with displaying user a prompt using sweetalert (that's kinda irrelevant)
Simplified HTML
<form class="form-horizontal" method="post" action="post.php?id=<?php echo $wid; ?>">
<button type="submit" name="submit1" class="btn btn-success">Submit #1</button>
<button type="submit" name="submit2" class="btn btn-warning">Submit #2</button>
<button type="button" class="btn btn-danger "onclick="remove()">REMOVE()</button>
</form>
PHP that form is submited to. I have to distinguish between buttons used so simplified:
if(isset($_POST['submit1'])){
//do stuff
} elseif(isset($_POST['submit2'])) {
//do second stuff
}
Finally JS code that displays the prompt:
function remove() {
var id = <?php echo $wid ?>;
swal({
title: "Sure?",
type: "warning",
}).then(function() {
swal({
title: "Removed!",
});
removeRow();
});
return false;
}
function removeRow() {
var id = <?php echo $wid ?>;
window.location = 'delete.php?&id=' + id;
}
However I cannot do the same prompt with those two submit buttons.
What's the issue there:
It has to be submit button otherwise PHP won't recognise which
button was used to submit
When i click submit button form automatically submits before "reading" javascript code (what's kinda logic) but even though I stop the event and then try to .submit() with jQuery it wont work out because I cannot submit a form from button-level so form won't pass name of button that was used to be submitted - won't work
How can i show user prompt and it holds submitting untill users accepts warning and yet be able to distinguish which button was used to submit it (so php get's submitted button name)?
I edited PHP into two separate files.
Afterwards I added two listeners on click on both of buttons. I removed submit type of them and then added jQuery code:
$( "#submit1" ).click(function() {
var id = <?php echo $wid ?>;
swal({
title: "Sure?",
type: "warning",
}).then(function() {
swal({
title: "Success!",
});
$('#formW').attr('action', 'script.php?id='+id);
$('#formW').submit();
});
return false;
});

jquery-confirm - submit clicked button in form with multiple buttons

I am using this very nice Jquery confirm plugin, problem is I am having issue with submit specific button in form with multiple buttons, my code works fine in php side without jquery-confirm plugin. It can get exact button submit value but I want to get confirmation before submit. Below is my scenario:
I have 2 delete submit buttons in single form and integrated with jquery-confirm. When I click on specific delete button (18), it submit the whole form, what I wanted is only the clicked button allowed to submit, below is my code:
<form action="" method="POST" id="messages">
<button type="submit" name="message_id" value="18" class="btn btn-danger confirmation" >Delete</button>
<button type="submit" name="message_id" value="17" class="btn btn-danger confirmation" >Delete</button>
</form>
Jquery code:
$('.confirmation').confirm({
content: 'Delete this message?',
title: 'Please confirm',
confirm: function(){
$('#messages :submit').submit();
}
});
So far, I have tried with this.$target.closest('#messages').submit();, with trigger('click') but they weren't working as expected.
If i add onclick="return confirm('Delete this message?');" inside button, it will trigger alert box and submit the selected button as expected, not the whole form submission. what I wanted is to get the value of the submitted button only, from PHP side when the button submitted. When I click on specific delete button ( value 18), I can catch the $_POST['message_id'] value = 18 without jquery-confirm plugin. But when I use jquery-confirm with submit(), from PHP side it could not catch any $_POST['message_id'] value .
See my jsfiddle for more details:
Try this approach.
$('button[type=submit]').on('click',function(e){
e.preventDefault(); // prevent submit button from firing and submit form
var $this = $(this);
$('.confirmation').confirm({
content: 'Delete this message?',
title: 'Please confirm',
confirm: function(){
$this.parent('form').submit(); // since user has confirmed action now submit form
}
});
});
OR
Create a small delete.php file where you can place the php code that handles the deletion of the message.
Use jQuery post() to submit your data after confirmation.
$('button[type=submit]').on('click',function(e){
e.preventDefault(); // prevent submit button from firing and submit form
var $this = $(this);
$('.confirmation').confirm({
content: 'Delete this message?',
title: 'Please confirm',
confirm: function(){
$.post( "delete.php", { message_id: $this.val() })
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
});
}
});
});
I found a workaround is to add hidden input with clicked message_id value, so everything is works fine for now, posted here in case of anyone else need this :
$('.confirmation').confirm({
content: 'Delete this message?',
title: 'Please confirm',
confirm: function(){
$('<input>').attr('type','hidden').attr('name', 'message_id').attr('value', this.$target.val()).appendTo('form');
$('#messages').submit();
}
});

sweetalert confirm doesn't return false on form submit

Similar question has been asked before but I did not find the replies useful to my requirement, hence this question.
Here is the form:
<form class="form-horizontal" role="form" method = "post" onsubmit = "return step1();" action = "index.php">
.....
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-floppy-o"></i> Save</button>
</form>
Here is the javascript function:
function step1() {
warn = "Some text";
swal({ title: "Warning!", text: "warn+"\nDo you still want to save this?", type: "warning", showCancelButton: true, confirmButtonColor: "#5cb85c", confirmButtonText: "Yes!", cancelButtonText: "Cancel!", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){ if (isConfirm) { swal("OK!", "Will proceed.", "success"); return true; } else { swal("Cancelled", "You may edit it.", "error"); return false; } });
}
Despite providing return false; when cancel button is clicked, the form gets submitted. How to make it work? Note: I am not comfortable with jquery.
You have to return from the step1() function in order to prevent the form from submitting.
You don't have any return statement there. Your return statement is in an anonymous function which looks like it gets passed as an argument (please format your code to make it readable!).
If you are going to represent your message using DOM manipulation (which is what I assume your library is doing) then you can't block the UI until you get a click.
The closest you could come would be to always prevent the form from being submitted, and then re-trigger the submission with JS when you got the OK click.

Categories

Resources