SweetAlert2 Confirmation on form submit not working with Codeigniter - php

I'm trying to make a confirmation popup before user submits the form with CodeIgniter but the trigger/submit part is not working. It asks for confirmation but doesn't submits the form.
My HTML:
<?php
echo form_open(site_url("action"), array('id' => "order" , )) ?>
<input type="text" class="form-control" name="anything" value="">
<button type="submit" id="btn-submit" class="btn btn-danger" class="form-control">Submit</button>
<?php echo form_close() ?>
And Here's the Javascript
$('#btn-submit').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();
});
});
I've also tried targeting/selecting form id instead button but same issue. Resources are loaded properly.

Change it:
var form = $(this).parents('form');
to
var form = $(this).parent('form');
and try again.

I was actually using wrong function. The function I used was from sweetalert while I loaded sweetalert2. I changed the code from
swal({
{... closeOnConfirm: false},
function() {
// Function
}
});
to
swal({
...
showLoaderOnConfirm: true,
preConfirm: function() {
//function
}).then(function() {
swal('Processing');
});
and it's working

Related

Confirm delete using swal on laravel 5.8

I got some troubles when using swal to confirm delete, I do not know how to make it work
here is my blade view file:
<form action="{{ route('user.destroy', $us->id)}}" method="post">
#method('DELETE')
#csrf
<input class="btn btn-danger" type="submit" value="Delete" />
</form>
and the script using swal
<script>
//== Class definition
var SweetAlert2Demo = function() {
//== Demos
var initDemos = function() {
$('.btn-danger').click(function(e) {
e.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
buttons:{
confirm: {
text : 'Yes, delete it!',
className : 'btn btn-success'
},
cancel: {
visible: true,
className: 'btn btn-danger'
}
}
}).then((Delete) => {
if (!Delete) {
e.preventDefault();
}
});
});
};
return {
//== Init
init: function() {
initDemos();
},
};
}();
//== Class Initialization
jQuery(document).ready(function() {
SweetAlert2Demo.init();
});
</script>
the version of swal is https://sweetalert.js.org not https://sweetalert2.github.io/
And I'm using route resource on laravel 5.8
thanks you!
Update in case of Loops
You should give an id to your form and then in the swal callback submit the form by using the ID
<form action="{{ route('user.destroy', $us->id)}}" method="post" id="yourFormId">
Your JS Click button is almost same. Just some small change in the Swal JS Callback Method
$('.btn-danger').click(function(e) {
var $form = $(this).closest("form"); //Get the form here.
e.preventDefault();
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
buttons:{
confirm: {
text : 'Yes, delete it!',
className : 'btn btn-success'
},
cancel: {
visible: true,
className: 'btn btn-danger'
}
}
}).then((Delete) => {
console.log(Delete); //This will be true when delete is clicked
if (Delete) {
$form.submit(); //Submit your Form Here.
//$('#yourFormId').submit(); //Use same Form Id to submit the Form.
}
});
});
Use GET method instead of POST.
And no need to use button or combine anything.
Try this example,which always works with my all projects.
As
Use anchor tag, Not button
<a class="btn btn-action text-danger" title="Delete" data-toggle="tooltip" onclick="deletefunction({{$your_id}})"><i class="fa fa-trash"></i></a>
Add Script As,
<script>
var deletefunction = function(id){
swal({
title: "Are you sure you want to Delete this?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
closeOnConfirm: false,
preConfirm: function(result) {
window.location.href = '{{url('/your_route/delete')}}/'+id;
},
allowOutsideClick: false
});
};
</script>

How to alert success message in modal form?

I'm new to ajax/jquery. I want to use sweetalert on my website, i set it up as in tutorial, but when i open modal form and click send button, it goes to another page, page send.php.
Here my form:
<form id="contactForm1" action="send.php" method="post">
<div class="field-block">
<label for="text">Message1</label>
<textarea id="message1" class="field" required name="message1" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message2</label>
<textarea id="message2" class="field" required name="message2" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message3</label>
<textarea id="message3" class="field" required name="message3" rows="4" placeholder=""></textarea>
</div>
<button id="button" class="button" type="submit">Отправить</button>
<div class="result">
<span id="answer"></span>
<span id="loader"><img src="images/loader.gif" alt=""></span>
</div>
</form>
inside this form sweetalert doesn't work, but outside of form it's working.
Here sweetalert jquery and ajax request:
<script>
$("#contactForm1").on('submit',function(event) {
event.preventDefault(); // to prevent default page reloading
var dataString = $(this).serialize(); // to get the form data
$.ajax({
type: "POST",
url: "send.php",
data: dataString,
success: function(data){
$('#contactForm1')[0].reset(); // to reset form data
}
}).done(function(data){
setTimeout(function () {
Swal.fire(
'Thank you!',
'Your request has been accepted!',
)
}, 2000);
});
});
</script>
what could be the problem? Please help
The problem is you're not sending request with AJAX.
Solution:
First remove action="send.php" from your form
then add this to your script.
<script>
$('.button').click(function(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
}).then((value) => {
<!-- When the user click submit send Ajax request -->
$.ajax({
url: "send.php",
method: "POST",
data:{
message1: $(#message1).val(),
message2: $(#message2).val(),
message3: $(#message3).val()
},
success: function(data)
{
// some actions
}
});
});
});
</script>
You can send it without ajax request also try this change
$('.button').click(function(){
to
function submitForm(){
your function will look like this:
function submitForm(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
});
}
Now in the form add
onsubmit="return submitForm()"
swal({ title: "Done", text: "Record updated successfully!", type: "success" }, function () {location.reload();});
Simply use this line code, it will automatically hide alert and reload the page when click "OK".

Jquery-confirm plugin doesn't submit button type="submit" inside jquery-validation?

I'm using https://jqueryvalidation.org/ plugin and https://craftpip.github.io/jquery-confirm plugin.
I've this code of script:
$("#form1").validate({
submitHandler: function(form) {
$.confirm({
title: 'Confirm',
content: 'Are you sure?',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-success',
action: function () {
form.submit();
}
},
cancel: {
text: "Annulla",
action: function () {
}
}
}
});
}
);
and the form:
<form id="form1" name="form1" action="index.php" method="post">
<input type="text" name="var1" value="1">
<input type="text" name="var2" value="2">
<input type="text" name="var3" value="3">
<button type="submit" class="btn btn-info" value="edit" name="action">EDIT</button>
</form>
the page itself index.php:
if ( isset($_POST['action']) && $_POST['action'] == "edit" ) {
echo "EDITED";
exit();
}
var_dump($_POST);
The problem is that button submit is not passed!! I don't know why. My var_dump says there are all 3 inputs type="text" but not the button.
I tried removing jquery-confirm and it's ok, all inputs and button type submit are passed:
$("#form1").validate({
submitHandler: function(form) {
form.submit();
}
);
I don't know how to solve. I don't know how to post an example with jsfiddle using $_POST and PHP.
Thats because submit() does not include the submit button. You'd have to push the value of the button manually.
An example on how this might be done:
$('document').ready(function() {
$("#form1").validate({
submitHandler: function(form) {
$.confirm({
title: 'Confirm',
content: 'Are you sure?',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-success',
action: function () {
let variables = $('#form1').serializeArray();
variables.push({name: $('#form1 button').attr('name'), value: $('#form1 button').attr('value')})
// Perform custom XHR here ($.ajax) with `variables`
}
},
cancel: {
text: "Annulla",
action: function () {
}
}
}
});
}
});
});
https://jsfiddle.net/n2gwjvqd/2/
PS: it makes sense to cache jquery selectors so
variables.push({name: $('#form1 button').attr('name'), value: $('#form1 button').attr('value')})
might become
let button = $('#form1 button');
variables.push({name: button.attr('name'), value: button.attr('value')})

Uploading image with DropZone and other values via AJAX but calling SweetAlert when Submit Data

I have a form with some fields (first name, last name and profile picture) that looks like this:
<form>
<div class="row">
<div class="col-lg-6">
<label class="control-label">First Name:</label>
<input class="form-control" type="text" placeholder="Enter first name.." id="firstName">
</div>
<div class="form-group col-lg-6">
<label class="control-label">Last Name:</label>
<input class="form-control" type="text" placeholder="Enter last name.." id="lastName">
</div>
</div> <!-- /row -->
<div class="row">
<div class="form-group col-lg-6">
<label class="control-label">profile picture:</label>
<div class="dropzone dropzone-previews" id="profilbildDropzone">
<div class="fallback">
<input name="file" type="file" multiple="multiple">
</div>
</div>
</div>
</div> <!-- /row -->
<hr />
<div class="form-action">
<button type="button" class="btn btn-primary waves-effect waves-light" id="sweet-ajax">Submit Data</button>
</div>
</form>
When the user clicks on submit data I call a Sweet-Alert dialog that asks if the user is sure about the action he tries. If he clicks yes I want to submit the data via AJAX to an PHP script that does all the rest (storing the image on the server, save the data in my database and so on):
<script type="text/javascript">
SweetAlert.prototype.init = function () {
//Ajax
$('#sweet-ajax').click(function () {
swal({
title: "Sure?",
text: "Clicking on yes submits the data!",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "Yes!",
cancelButtonText: "Cancel",
showLoaderOnConfirm: true,
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger m-l-10',
preConfirm: function(givenData){
return new Promise(function(resolve, reject) {
setTimeout(function(){
inputNameFirst = document.getElementById("firstName").value;
inputNameLast = document.getElementById("lastName").value;
resolve()
}, 2000)
})
},
allowOutsideClick: false
}).then(function(givenData){
$.ajax({
type: "post",
url: "../assets/php/addUser.php",
data: {done: "success", fN: inputNameFirst, ln: inputNameLast},
dataType: 'JSON',
success: function(data) {
if(data.status === 'success'){
swal({
type: 'success',
title: 'Good job!',
html: 'all saved now!'
})
}else if(data.status === 'error'){
swal({
type: 'error',
title: 'Oh No!!',
html: 'Nope sorry, there was an error: <br /><pre>'+ JSON.stringify(data) + '</pre>'
})
}
}
})
}, function(dismiss) {
// dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
if (dismiss === 'cancel') {
swal(
'Got you!',
'Nothing changed. Good luck.',
'error'
)
}
})
});
},
//init
$.SweetAlert = new SweetAlert, $.SweetAlert.Constructor = SweetAlert
}(window.jQuery),
//initializing
function ($) {
"use strict";
$.SweetAlert.init()
}(window.jQuery);
</script>
I also set up the DropZone on my site so that I can also have optional fields in my form (from here):
jQuery(document).ready(function() {
$("div#profilbildDropzone").dropzone({
//store images in this directory
url: "../assets/images/uploads",
dictDefaultMessage: "Drop image here or click.",
autoProcessQueue: false,
maxFiles: 1,
uploadMultiple: true,
parallelUploads: 100,
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button#sweet-ajax").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
});
});
But I do not get it how I upload the picture or give it so my php script.
In this line:
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
I'm supposed to upload the picture or what? Can I call this function inside my SWAL function or pass the data to my SWAL function where it gets send to the PHP script?
Sadly I haven't found any usable example that gives me a clear hint on how I could solve this specific problem.
You are not written logic send data via ajax to server side (i.e PHP). On click of the submit button you are telling Dropzone.js to processQueue(). But that itself will not post the data to the server via ajax.
On sendingmultiple event you need to get form data and assign it to formObject, then DropzoneJS will take care of posting data along file/image to the PHP.
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button#sweet-ajax").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Append all form inputs to the formData Dropzone will POST
var data = $form.serializeArray();
$.each(data, function (key, el) {
formData.append(el.name, el.value);
});
});
}
Next on the PHP server side get the posted data and files/images likes this.
<?php
//get form data
echo '<pre>';print_r($_POST);echo '</pre>';
//get posted files
echo '<pre>';print_r($_FILES);echo '</pre>';
exit;
Next write your logic upload files/images and also updating the database with posted data.
Also check I have written detailed tutorials on how to upload images with form data on button click using DropzoneJS and PHP via ajax.
Ajax Image Upload Using Dropzone.js with Normal Form Fields On Button Click Using PHP

Jquery Submit Ajax

I can't seem to make this to work. I'm trying to submit form using jquery dialog and I want to receive in php so I can use $_POST.
Any idea?
HTML:
<div id="table_rows_form">
<form id="fieldsform" action="system/create">
<label for="fields">How many fields are needed?</label>
<input type="text" id="fields" name="fields" />
<button type="submit">Submit</button>
</form>
</div>
Javascript:
$(document).ready(function() {
$('#table_rows').on('click', function() {
$('#table_rows_form').dialog({
open: function() {
$(this).find('[type=submit]').hide();
},
draggable: true,
modal: true,
resizable: false,
closeOnEscape: false,
width: 'auto',
minHeight: 235,
title: 'Number of Fields',
dialogClass: 'no-close',
buttons: {
"Send": function() {
$('#fieldsform').submit(function(event) {
var formData = {
'fields': $('input[name=fields]').val()
};
$.ajax({
type: 'POST',
url: $('#fieldsform').attr('action'),
data: formData,
dataType: 'json',
encode: true
});
});
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
return false;
});
});
PHP:
print_r($_POST);
The dialog opens correctly but when pressing send button doesn't do anything and doesn't gives any error at the console. Any idea about the error? I'm a newbie with jquery.
You're just adding a submit handler with your code $('#fieldsform').submit( ... ) so it doesn't trigger anything.
Rather, you should do that on document ready, and in the click handler for "Send" button, call $('#fieldsform').submit();

Categories