I am trying to use sweet alert in yii in place on the confirmation option.
I have an ajax button and I would like the sweet alert to pop up, once the user has chosen confirm or cancel I can then either continue with the ajax request or stop.
'ajax' => array(
'url'=>CController::createUrl('items/delete'),
'type'=>'POST',
'async'=>true,
'data'=>array('Item'=>$item['Item_id']),
'dataType'=>'json',
'enctype'=>'multipart/form-data',
'cache'=>false,
'beforeSend'=>'js:function(data)
{
var x = sweetalertDelete();
if(x){alert("aaaaaaa"); return true;}
else {alert("bbbbb"); return false;}
}',
'success'=>'function(data)
{
I am using beforesend in order to display the sweet alert box. The issue is that as soon as the the box appears, x is returned and the alerts seen later are then shown. Here is my sweet alert code:
function sweetalertDelete(){
swal({
title: "<?php echo Yii::t('app','misc.order_delete'); ?>",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
//swal("Deleted!", "Your imaginary file has been deleted.", "success");
if (isConfirm) {
alert("true");
return true;
}
else
{
alert("false");
return false;
}
});
}
My question is how I can make it so that the value of isconfirm is returned and until the confirm/cancel button is clicked, the ajax request will not be sent.
Related
I'm trying to show the sweet alert in my DELETE FEATURE but sadly my code now is not working I already search for similar feature I see some but it not help me thought. Here is my code
<a id="<?php echo $id;?>" value="<?php echo $id;?>" name="delete" onclick="archiveFunction(this.id)">
<i class="glyphicon glyphicon-trash text-red"></i></a>
And this is my ajax request
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
$('#reloadpage').click(function() {
location.reload(true);
});
function archiveFunction(id) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure?",
text: "But you will still be able to retrieve this file.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Delete it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
// this is `post` request to the server
// so you can get the data from $_POST variables, says $_POST['delete'] $_POST['v_id']
$.ajax({
method: 'POST',
data: {'delete': true, 'id' : id },
url: 'user_del.php',
success: function(data) {
}
});
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
And this is my archive query . Don't bother about my query I set the status to 0 for me to archive one data and it will go to archive page. I just want to display the SWEET ALERT when I'm deleting the data or archiving it. Thanks in advance.
<?php session_start();
if(empty($_SESSION['id'])):
header('Location:../index');
endif;
include("../dist/includes/dbcon.php");
$id=$_REQUEST['id'];
$result=mysqli_query($con,"UPDATE accounts_at SET status = 0 WHERE id ='$id'")
or die(mysqli_error());
if ($result !== false) {
echo "<script type='text/javascript'>alert('Successfully deleted a account!');</script>";
echo "<script>document.location='index'</script>";
}
?>
Your UPDATED alert is in the wrong spot if you want it to run after the object is officially deleted on the server.
function(isConfirm){
if (isConfirm) {
// this is `post` request to the server
$.ajax({
method: 'POST',
data: {'delete': true, 'id' : id },
url: 'user_del.php',
success: function(data) {
//if you put it here it will run after the file is deleted
swal("Updated!", "Your imaginary file has been Deleted.", "success");
}
})
//if you put it here it will run before and even if your file is not deleted
// swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
Open up the develop console in your web browser. Does it give you any errors?
Do you get any alerts at all?
try this:
function archiveFunction(id) {
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) return;
$.ajax({
url: "delete.php",
type: "POST",
data: {
id: id
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}
I wanted to pause form's onsubmit, so I could ask user to confirm action before proceed.
So here's my form:
<form action="<%= request.getContextPath()%>/Controller"
method="POST" id="remove_book"
onsubmit="alertBookInfo('return_book')">
</form>
Then, I created the JavaScript function, using SweetAlert:
function alertInfo(action) {
document.querySelector(action).addEventListener('submit', function (e) {
var form = this;
e.preventDefault();
if (action === "remove_book") {
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function () {
form.submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
});
}
But for some reason, I am unable to prevent page reload on form submit. Am I doing someting wrong?
PS: I already tried with return alertInfo() in form and returning boolean value from JS function with no success.
Why not call the function from the form like this, the the alert will be prompt before submitting the form:
HTML
<form action="<%= request.getContextPath()%>/Controller" method="GET" id="remove_book" onclick="myAlertFunction(event)">
<input type="submit">
</form>
JavaScript
function myAlertFunction(event) {
event.preventDefault()
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function() {
$("#remove_book").submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
And if you want to prevent the reload, you can always use event.preventDefault()
Here is an example: JSFiddel
If you don't want the page reloads you could use an AJAX call. When you use the submit() you will always reload the page because is how submit works.
$.ajax({
method: "POST",
url: YOUR_ACTION_URL,
data: $('form').serialize(),
success: function(data){
//here you could add swal to give feedback to the user
}
});
In your controller you have to define the method as produces JSON, if you are using Spring, the annotation is #ResponseBody
I have Categories listed in a view. A delete category button is also there in the view which does work and deletes the category when clicked.
What I want to do is before deleting a category, a sweet alert dialog to pop up and ask for confirmation. If confirmed, it should go to the defined route and delete the category.
The delete link is defined like this:
<a id="delete-btn" href="{{ route('admin.categories.destroy', $category->id) }}" class="btn btn-danger">Delete</a>
and the script is defined like this:
<script>
$(document).on('click', '#delete-btn', function(e) {
e.preventDefault();
var link = $(this);
swal({
title: "Confirm Delete",
text: "Are you sure to delete this category?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: true
},
function(isConfirm){
if(isConfirm){
window.location = link.attr('href');
}
else{
swal("cancelled","Category deletion Cancelled", "error");
}
});
});
</script>
However, when I click the delete button it deletes the category, but the sweet alert message doesn't show up.
The route is defined as following:
Route::get('/categories/destroy/{category}', [
'uses' => 'CategoriesController#destroy',
'as' => 'admin.categories.destroy',
]);
and the controller function is defined as:
public function destroy(Category $category)
{
$category->delete();
//this alert is working fine. however, the confirmation alert should appear
//before this one, which doesn't
Alert::success('Category deleted successfully', 'Success')->persistent("Close");
return redirect()->back();
}
Any help would be appreciated. Thanks.
Try this:
<script>
var deleter = {
linkSelector : "a#delete-btn",
init: function() {
$(this.linkSelector).on('click', {self:this}, this.handleClick);
},
handleClick: function(event) {
event.preventDefault();
var self = event.data.self;
var link = $(this);
swal({
title: "Confirm Delete",
text: "Are you sure to delete this category?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: true
},
function(isConfirm){
if(isConfirm){
window.location = link.attr('href');
}
else{
swal("cancelled", "Category deletion Cancelled", "error");
}
});
},
};
deleter.init();
</script>
EDIT: From your comment at #kalyan-singh-rathore's answer, I think you're not properly injecting the script in your blade template. If you're extending a base layout, make sure you've included the script or yielded it from a child layout.
Write anchor in below way.
Delete
Now in URL select change href to customParam.
function (isConfirm) {
if (isConfirm) {
window.location = link.attr('customParam');
} else {
swal("cancelled", "Category deletion Cancelled", "error");
}
}
Basically in your case both href and event lisner are on click.
Try this one it worked out for me :)
document.querySelector('#promote').addEventListener('submit', function (e) {
let form = this;
e.preventDefault(); // <--- prevent form from submitting
swal({
title: "Promote Students",
text: "Are you sure you want to proceed!",
type: "warning",
showCancelButton: true,
// confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
closeOnConfirm: false,
closeOnCancel: false,
dangerMode: true,
}).then((willPromote) => {
e.preventDefault();
if (willPromote.value) {
form.submit(); // <--- submit form programmatically
} else {
swal("Cancelled", "No students have been promoted :)", "error");
e.preventDefault();
return false;
}
});
});
I am using Meteor and Aldeed's Autoform. I want to check that the user is certain before submission takes place. I have tried many things but when I press the button, the form submits anyway. Here's what I have now, which produces a modal nicely (with SweetAlert) even though submission occurs in the background anyway:
AutoForm.hooks({
createEventForm: {
before: function() {
this.event.preventDefault();
},
beginSubmit: function() {
this.event.preventDefault();
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: true },
function(){
swal("Deleted!", "Your imaginary file has been deleted.", "success"); });
},
How can I make the form wait for the user to confirm or cancel the operation?
Thanks!
The beginSubmit is called at the beginning of the form submission. As the documentation states, it can be used to disable/enable buttons or showing a wait message when submitting longer requests. If you want to display a confirmation message and submit the form depending on the user's decision, you need to use the before hook.
For example:
AutoForm.hooks({
createEventForm: hooksObject
});
var hooksObject = {
before: {
insert: function(doc) {
var self = this;
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: true
}, function(isConfirm) {
if (isConfirm) {
/* Submit form: */
self.result(doc);
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
/* Async cancel form submission: */
self.result(false);
}
});
}
}
}
I'm using the sweet alert library and I have a problem with the cancel button. This is my code for the sweet alert:
sweetAlert({
title: title,
text: text + ' ' + courseList,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: confirmButtonText,
cancelButtonText: "Continue with purchase",
closeOnConfirm: false,
closeOnCancel: false,
html: true
},
function(isConfirm) {
if (isConfirm) {
angular.forEach(repeatedCourses, function(repeatedCourse) {
$rootScope.$apply(function() {
this.removeCoursePurchase(repeatedCourse);
}.bind(this));
}.bind(this));
$rootScope.$broadcast('uncheckCheckboxes');
swal("Deleted!", "Your purchase has been refreshed.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
}.bind(this));
When the user click on the confirm button, works fine, but If the cancel button is clicked doesn't do anything, it doesn't appear the "Cancelled" box and I don't know why!
Remove the .bind(this) attached to the callback function and it will work.