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

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();
}
});

Related

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;
});

Javascript form submit doesn't submit properly

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.

Javascript have to click button twice which is outside the form

Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.

Trigger form submit with multiple submit buttons

I have a form with two submit buttons, Rails backend expects to receive one of the button names (action1 or action2) in the params hash. I want to show "are you sure?" message on one of the buttons. I have this code:
<form action="/models" id="myform" method="post">
<input name="action1" id="action1Button" type="submit" value="Make Action 1">
<input name="action2" type="submit" value="Make Action 2">
</form>
$('#action1Button').click(function() {
$('#popup').modal('show');
// cancel a submit
return false;
});
$('#popupSubmitButton').click(function() {
$('#myform').submit(); // I want this to trigger action1
});
$('#popupCancelButton').click(function(){
$('#popup).modal('hide');
});
The problem is that when form submits there is no name of the submitted button in the request. Is there a way to submit a form as though as submit button was actually clicked?
Trigger the event with trigger(), and in the event handler you can actually check if the event was triggered or not by checking event.isTrigger
$('#action1Button').on('click', function(e) {
if (!e.isTrigger) {
$('#popup').modal('show');
return false;
}
});
$('#popupSubmitButton').on('click', function() {
$('#action1Button').trigger('click');
});
$('#popupCancelButton').on('click', function () {
$('#popup').modal('hide ');
});
FIDDLE

Categories

Resources