form.submit(); does not run action of form - javascript

I have a Laravel 5.8 project with using sweetalert.js.
And I have a form like this:
<form id="myForm" action="{{ route('acceptWallet') }}" method="POST">
#csrf
<input type="checkbox" id="btn-submit" name="wallet_checked" onchange="this.form.submit();">
</form>
And then, here is the route acceptWallet:
Route::post('course/accept/wallet','Wallet\WalletController#acceptWallet')->name('acceptWallet');
And at the method acceptWallet of WalletController, I have added this:
public function acceptWallet(Request $request)
{
dd($request->wallet_checked);
}
As you can see I have used onchange="this.form.submit();" to submit the form without using submit button and it works fine.
Then by using this script, I tried showing SweetAlert confirmation message box, containing Yes and No as buttons:
$(document).on('click', '#btn-submit', function(e) {
e.preventDefault();
let form = $(this).parents('form');
swal(
{
title: "Attention!",
text: "Are you sure you want to make this transaction",
type: "warning",
allowEscapeKey: false,
allowOutsideClick: false,
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
showLoaderOnConfirm: true,
closeOnConfirm: false
}).then((isConfirm) => {
if (isConfirm) {
form.submit();
return true;
}
return false;
});
});
As you can see I have used form.submit(); if user clicks on Yes button in order to submit the form.
But now the problem is, the form does not submitted and just refreshes the page and not showing dd($request->wallet_checked); as result.
So what's going wrong here? How can I properly submit the form after showing SweetAlert popup message?
I also tried document.forms['myForm'].submit(); instead of form.submit(); but didn't submit the form.

May be your let form = $(this).parents('form'); havent find the form correctly. So just console.log(form) and check is it available.
Also since there is a id for your form you can do something like below.
}).then((isConfirm) => {
if (isConfirm) {
document.getElementById("myForm").submit();
//Or $('#myForm').submit();
return true;
}
return false;
});
Or jest make your variable with jquery via id
let form = $('#myForm')

Related

How to use sweetalert / swal correctly?

I am new in Javascript / jQuery. I want to show some alert message using 'sweetalert' library and based on the user response the function will either return or continue.
Here is my implementation :
jQuery("#some_exchnage_request_form").on( 'submit', function(e){
// some implementation
// Now showing the alert
jQuery.getScript('https://unpkg.com/sweetalert/dist/sweetalert.min.js', function() {
swal({
title: "Do you want Continue ? ",
text: "You need to pay extra amount",
icon: "success",
buttons: true,
confirmButtonColor: '#C64EB2',
})
.then((willSubmit) => {
if (!willSubmit) {
return false;
}
});
});
// rest of the code
});
Here the expectation is if the user select 'cancel' button the function should return false, otherwise on selecting 'ok' button 'rest of the code' portion to be executed.
But here problem is the code doesn't stop for the user input and just continue. The alert box is displayed but it ignore the user selection.
I know implementation is wrong, but not sure what would be the correct way to do this.
Thanks!!
You need to use Swal.fire(); to make it work.
https://sweetalert2.github.io/
jQuery("#some_exchnage_request_form").on( 'submit', function(e){
// some implementation
// Now showing the alert
e.preventDefault();
jQuery.getScript('https://cdn.jsdelivr.net/npm/sweetalert2#11', function() {
Swal.fire({
title: 'Do you want Continue ?',
text: "You need to pay extra amount",
icon: 'success',
showCancelButton: true,
confirmButtonColor: '#C64EB2',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Confirmed!',
'You agreed to pay extra amount.',
'success'
)
} else {
console.log('clicked cancel');
}
})
})
// rest of the code
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="some_exchnage_request_form">
<input type="submit">
</form>
There are similar questions and looks like it is a limitation of 'sweetalert' that execution doesn't stop for user input unlike alert()/confirm() in js.
sweetalert pause execution and return value
How to return the value of SweetAlert2 input?

Unable to submit form in javascript after sweet alert has been closed

I have created an application that will feature a demo login. The Demo login will have a sweet alert pop up to let the user know that the changes they make will not be saved to the database. The problem is that the form doesn't submit after the user presses ok button that will close the sweet alert. What is the proper syntax to submit the form after the ok button has been pressed?
Below is my html:
<form method="post" id="submitForm" name="demoSubmitForm">
<div class="demo-button pt-3">
<button type="button" name="demoEmail" value="DemoEmail" class="au-btn au-btn--block au-btn--blue
m-b-20" onclick="ShowSweetAlert()">
Demo Application
</button>
</div>
</form>
Below is my script:
function ShowSweetAlert() {
Swal.fire({
icon: 'warning',
title: 'You are logging in as a Demo User!',
text: 'Changes you make to the Application will not be saved once you log out.',
onClose: document.getElementById('submitForm').submit() /*document.demoSubmitForm.submit()*/
});
}
At the moment neither do document.demoSubmitForm.submit() nor document.getElementById('submitForm').submit() work in order to submit the form.
Video of the Problem
Add this Script:
$('#submitForm').on('click', function(e) {
e.preventDefault();
var form = $(this).parents('form');
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(isConfirm) {
if (isConfirm) form.submit();
});
});

SweetAlert Calling code after clicking "Cancel" button

I have written following code, I want to call a code under "Cancel" button:
vm.saveGroup = function(){
SweetAlert.swal({
title: "Name this Device Group",
text: "Please provide a name that you want your device group to be saved under. Also, make sure that you already specified all needed filters before you save the list.",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
inputPlaceholder: "Device Group name"
},
function(inputValue){
if (inputValue === false) {
return false;
}
if (inputValue === "") {
/*eslint-disable */
swal.showInputError("You need to write something!");
/*eslint-enable */
return false;
}
deviceGroupsFactory.saveGroup(inputValue, vm.filterOutput)
.then(function(response){
if (response.status == 200){
SweetAlert.swal("Device Group saved!", "You should now see your device group on the list.", "success");
$state.go('main.template.devices.groups');
}
else {
SweetAlert.swal("Error!", response.statusText, "error");
console.log('xxx');
}
});
});
}
but I cannot call "cancel clicked". I was looking for in docs but cannot find the solution.
You're passing too many parameters to the swal constructor. It needs only two:
swal(options, callback)
options: Attributes to design the alert
callback: The callback function to manage the events
When you use a simple confirm, the callback receive only one parameter that indicates the user choice:
true: Confirm
false: Cancel
With inputbox you will receive the user's input string as parameter.
When you merge together inputbox and confirm, you could receive:
the input string value: When the user press Confirm
false: When user press Cancel
So, you have to use the Strict Equality Comparison in order to know if user pressed cancel or have inserted the string false in the input box.
Please see the following simple example:
swal({
title: "Are you sure?",
text: "Press CANCEL, please!",
type: "input",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "CONFIRM",
cancelButtonText: "CANCEL",
closeOnConfirm: false,
closeOnCancel: false
},
function(inputValue){
//Use the "Strict Equality Comparison" to accept the user's input "false" as string)
if (inputValue===false) {
swal("Well done!");
console.log("Do here everything you want");
} else {
swal("Oh no...","press CANCEL please!");
console.log("The user says: ", inputValue);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js"></script>
I hope it helps you, bye.
you can also use the implementation of promises using .then
I give you an example, this would be executed just after pressing the button
swal( 'Error!',valido.msj,'error').then((e)=>{
if( valido.msj=="Enlace de botón No Válido" ){
document.getElementById('link_btn_barra').focus();
}
});

MVC post losing values when submitted via javascript

I have an MVC form with a submit button:
<form method="POST" id="submitProject" action="#Url.Action(SubmitProject, "ProjectSummary")">
<button type="submit" name="submitButton" id="submitProject" value="saveToProposed" class="btn btn-primary">Submit Project</button>
</form>
But when a user clicks on that button i want to show them a confirmation dialog before the post goes on its way:
$('#submitProject').submit(function (e) {
var currentForm = this;
e.preventDefault();
bootbox.dialog({
message: "Approve or Reject",
title: "Project Approval",
buttons: {
success: {
label: "Approve",
className: "btn-success",
callback: function () {
alert("Approved");
currentForm.submit();
}
},
danger: {
label: "Reject",
className: "btn-danger",
callback: function () {
alert("Rejected");
currentForm.submit();
}
},
main: {
label: "Cancel",
className: "btn-primary",
callback: function () {
return true;
}
}
}
});
});
in my controller i am trying to trap the value of the submit button like this:
[HttpPost]
public ActionResult SubmitProject(ProjectModel m, string submitButton)
{
}
if i do not have that preventDefault line in there i can see the value of the submitButton in the controller. With the preventDefault the value is always null.
this is something i have been struggling with for some time as i try to learn MVC. if i didn't have any client side interaction i would be fine. But trying to get js to play with mvc is giving me hearburn. what am i doing wrong?
A form only posts back the name/value pair of its submit button that was clicked. In your case your cancelling the buttons .click() event and then calling the .submit() function (i.e. the submit is no longer triggered by the click so its value is not sent in the request).
Rather than calling e.preventDefault();, call a function that returns true or false, in the same way that you can use the javascript .confirm() function to cancel the form submission (i.e. return confirm("...");
function confirmSubmit()
{
bootbox.dialog({
....
// for the success and danger buttons - return true;
// for the main button - return false
buttons: {
success: {
label: "Approve",
className: "btn-success",
callback: function () {
return true;
}
},
....
});
}
$('#submitProject').submit(function (e) {
return confirmSubmit();
});
Side note: your form only has one submit button, so the value of string submitButton will only ever be "saveToProposed". Not sure if you omitted it from your code, but I assume you would really have at least 2 submit buttons.

prevent a form from being submitted with SweetAlert

My goal is to only allow form submission after user clicks "Ok" on a SweetAlert box.
So, he clicks on an image (form), box appears with some instructions, he reads and clicks on "Ok", and then the form is submitted.
Here is the form code:
<form id="formpag" action="https://example.com/request.html" method="post">
<input type="hidden" name="code" value="7055C88A445678A00461CFA120F4A2E7" />
<input type="image" src="https://example.com/buttons/subscriptions/120x53-subscribe.gif" name="submit" alt="Pay with Example.com - it is fast and reliable!" />
</form>
Now the jQuery/Sweet Alert part:
jQuery( document ).ready(function( $ ) {
$(function() {
$('#formpag').submit(function() {
swal({ title: "Be Advised",
text: "You need to check your email account after payment.",
imageUrl: "images/thumbs-up.jpg" });
});
});
});
Problem: as it is now, box is showing to user, but after a few seconds, the form is being submitted, even without him clicking the OK button on the SweetAlert box.
Form must only be submitted if he clicks "OK".
Any help would be much appreciated. (sorry, I know it is a silly question, but SweetAlert documentation did not help me).
You need to prevent the default handling. Update your function to following
$('#formpag').submit(function(event) {
event.preventDefault();
swal({ title: "Be Advised",
text: "You need to check your email account after payment.",
imageUrl: "images/thumbs-up.jpg" });
});
});
For reference - http://api.jquery.com/event.preventdefault/
I have done it. I found another SweetAlert code, more suitable to my need, and I could mix it to a jquery basic function.
Here is the final result:
jQuery( document ).ready(function( $ ) {
$(function() {
$('#formpag').submit(function() {
event.preventDefault();
swal({
title: "Be advised",
text: "You need to check your email account after payment.",
type: "warning",
showCancelButton: false,
confirmButtonColor: 'blue',
confirmButtonText: 'Ok, got it.',
closeOnConfirm: false,
},
function(){
$('#formpag').submit();
});
});
});
});

Categories

Resources