function remove(){
console.log(xxx());
if(xxx() != true){
console.log(xxx());
return;
}
console.log('removed');
}
function xxx(){
SweetAlert.swal({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55"},
function(isConfirm){
if (isConfirm) {
return true;
} else {
return false;
}
}
);
}
How to get return from function xxx().
That's always return undefined when i fire remove().
If return is true i want to do console.log('removed').
As mentioned in the comments, your calling function has no access to the result of the callback function, however you can supply your wrapper xxx function with your own callback to be passed. Therein you have the choice of supplanting the callback entirely or for example pass only the action to be undertaken on success:
function remove(){
xxx(function(){console.log('removed');});
}
function xxx(OnSuccess){
SweetAlert.swal({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55"},
function(isConfirm){
if (isConfirm && OnSuccess)
OnSuccess();
}
);
}
Related
I have designed a simple ajax request for deleting a file from database in mvc. for that i am using javascritp ajax with swal prompt for delete. But it is not working. I am getting .then undefined error.
Here is the code--
$(".btnDel").click(function () {
var NewFileName = $(this).val();
var id =#Model.Pd.Id;
console.log(id);
console.log(NewFileName);
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
icon: "warning",
buttons: [
'No, cancel it!',
'Yes, I am sure!'
],
dangerMode: true,
})
.then(function (isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "#Url.Content("~/ManageProducts/DeleteExistingFile")/",
data: { 'id': id, 'fileName': NewFileName },
success: function (data) {
swal("Message.", data, "success");
location.reload();
},
error: function () {
swal("", "Something went wrong", "error");
}
});
}
else
{
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
});
Thanks for the edit. The snippet below defines id and NewFileName for testing and uses example.com for the POST - if you try to delete the file you get the "oops" message. In other respects it should be the same as the code in the post.
const id = "example_id";
const NewFileName = "example.pdf";
//**********************************
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
icon: "warning",
buttons: [
'No, cancel it!',
'Yes, I am sure!'
],
dangerMode: true,
})
.then(function (isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "https:www.example.com/delete",
data: { 'id': id, 'fileName': NewFileName },
success: function (data) {
swal("Message.", data, "success");
location.reload();
},
error: function () {
swal("", "Something went wrong", "error");
}
});
}
else
{
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
I am at a loss to explain why the snippet works but running it in VS says swal returns undefined. I would test the code in a browser first to see if it still errors.
Disclaimer: this is not the answer. . . yet. I am happy to delete it if anyone solves the mystery.
This is my code before add sweetalert2 to delete posts:
if (action == "delete") {
this.model.destroy({
beforeSend: function() {
target.addClass('loading');
view.blockUi.block(view.$el);
},
success: function(result, status, jqXHR) {
view.blockUi.unblock();
target.removeClass('loading');
if (status.success) {
if (result.get('post_type') == "post")
window.location.href = status.redirect;
else
view.$el.fadeOut();
} else {
// Error
}
}
});
return false;
}
this is my edit to make sweetalert2 compatible with the action:
if (action == "delete") {
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function () {
swal(
'Deleted!',
'Your post has been deleted.',
'success'
),
this.model.destroy({
beforeSend: function() {
target.addClass('loading');
view.blockUi.block(view.$el);
},
success: function(result, status, jqXHR) {
view.blockUi.unblock();
target.removeClass('loading');
if (status.success) {
if (result.get('post_type') == "post")
window.location.href = status.redirect;
else
view.$el.fadeOut();
} else {
// Error
}
}
})
});
return false;
}
I can't find the mistake the sweetalert2 dialog working right but the action of delete post not working, What can I do?
I can't find the mistake the sweetalert2 dialog working right but the action of delete post not working, What can I do?
When you initially call sweetalert it prompts for a response from the user.
The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.
If the user confirms, then you can execute the code. You already implemented a way to catch success and error, so when either of those happen, you just need to call sweetalert again to over ride the previous and display the correct alert to the user. You can do the same, optionally, for if the user decides to cancel to give them more feedback.
I believe that this would do the trick:
if (action == "delete") {
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function () {
this.model.destroy({
beforeSend: function() {
target.addClass('loading');
view.blockUi.block(view.$el);
},
success: function(result, status, jqXHR) {
view.blockUi.unblock();
target.removeClass('loading');
if (status.success) {
// Success
swal(
'Deleted!',
'Your file has been deleted.',
'success'
)
} else {
// Error
swal(
'Failed',
'Your file has not been deleted',
'error'
)
}
}
})
}, function () {
// Cancelled
swal(
'Cancelled',
'Your file has not been deleted',
'error'
)
});
return false;
}
I have a function on click for which I use sweetalert2. This is the function:
publish = function (article) {
swal({
title: "Skal du publisere?",
text: null,
type: "info",
showCancelButton: true,
cancelButtonText: "Avbyrt",
cancelButtonColor: '#FFF',
confirmButtonColor: "#2E112D",
confirmButtonText: "Ja, publisere"
}).then(function(){
var articleId = $(article).val();
$.post("/admin/articles/publish/article", {
'_token' : $('meta[name="csrf-token"]').attr('content'),
'articleId': articleId
}).done(function(){
$(article).hide();
return swal({
type: 'success',
title: 'Du har publisert den artikkel.',
showConfirmButton: false,
timer: 1000
});
}).fail(function() {
return swal({
type: 'warning',
title: 'Noeting gikk feil, prov igjen',
showConfirmButton: false,
timer: 1000
});
});
}, function(dismiss) {
// dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
}
Everything works fine but I get an error for the timer:
sweetalert2.min.js:1 Uncaught (in promise) timer
How can I avoid that, what am I doing wrong?
The problem is that you should generally never call a function that returns a promise without doing something with that promise. In this case the promise-returning functions are swal and $.post. If you ignore the returned promise then you're not waiting for it to complete. Your then handlers can return a promise to continue the promise chain, like this:
publish = function (article) {
return swal({
title: "Skal du publisere?",
text: null,
type: "info",
showCancelButton: true,
cancelButtonText: "Avbyrt",
cancelButtonColor: '#FFF',
confirmButtonColor: "#2E112D",
confirmButtonText: "Ja, publisere"
}).then(function(){
$(article).hide();
var articleId = $(article).val();
return $.post("/admin/articles/publish/article", {
'_token' : $('meta[name="csrf-token"]').attr('content'),
'articleId': articleId
}).then(function(){
return swal({
type: 'success',
title: 'Du har publisert den artikkel.',
showConfirmButton: false,
timer: 1000
}).catch(function(timeout) { });
});
}, function(dismiss) {
// dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
.catch(function(err) {
console.error(err);
throw err;
})
}
You need to add a rejection handler to the Promise. Alternatively, you can use .catch(swal.noop) as a quick way to simply suppress the errors:
swal('...')
.catch(swal.noop);
This issue is mentioned in the package documentation: https://github.com/limonte/sweetalert2#handling-dismissals
Also, there's the closed issue about the subject: limonte/sweetalert2#221
I have a C# method which performs a suspend operation.
protected void SuspendButton_OnClick(object sender, EventArgs e)
{
var accountNumberId = DepositAccount.DepositAccountNumberId;
var depositAccount = AccountHolders.GetAccountHolder(accountNumberId);
if (depositAccount == null)
{
ShowFailModal("No Account Selected");
}
Common.Deposit.AccountSuspension accntSuspension = new Common.Deposit.AccountSuspension();
accntSuspension.AuditTS = BusinessLayer.Core.DateConversion.GetCurrentServerDate();
accntSuspension.AuditUserId = UserId;
accntSuspension.Description = DescriptionTextBox.Text;
accntSuspension.SuspendedDate = GetDate;
accntSuspension.AccountNumberId = accountNumberId;
if (depositAccount != null)
{
InsertSuspendedAccount(accntSuspension);
}
}
I am using BootBox for the same now
$('#SuspendButton').on('click', function (evt) {
evt.preventDefault();
var message = "Are you sure you want to Suspend this Account?";
bootbox.confirm(message, function (result) {
if (result === false) {
evt.preventDefault();
} else {
// $.showprogress("Account Suspending.Please Wait...");
window.__doPostBack("<%= SuspendButton.UniqueID %>", "");
}
});
});
This is the sample of SweetAlert:
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(){
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
How can i make it work like BootBox?Like in BootBox, when i press the SuspendButton, it throws a bootbox.confirm popup, and if i press O,K the underlying operation is performed.Can i do that same with SweetAlert?
You can try something like this, let me know if this is not what you want
$('#SuspendButton').on('click', function (evt) {
evt.preventDefault();
//var message = "Are you sure you want to Suspend this Account?";
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) {
// $.showprogress("Account Suspending.Please Wait...");
window.__doPostBack("<%= SuspendButton.UniqueID %>", "");
} else {
evt.preventDefault(); }
});
});
try this,
First of all put your sweet alert code in some function lets say 'Suspend()'
eg:
function Suspend()
{
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(){
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
}
Now on the .aspx/.cshtml side assign the function name in "onClick()"
eg :
<input type="submit" value="Suspend" onclick='return Suspend();' title="Suspend" />
I am trying to override javascript confirm box with SweetAlert.
I have researched also about this but I can't found proper solution.
I am using confirm like this
if (confirm('Do you want to remove this assessment') == true) {
//something
}
else {
//something
}
And I am using this for overriding
window.confirm = function (data, title, okAction) {
swal({
title: "", text: data, type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
}, function (isConfirm) {
if (isConfirm)
{
okAction();
}
});
// return proxied.apply(this, arguments);
};
Now confirm box is replaced with sweetalert.
When user click on Yes button then OK action of confirm box should be called. But this isn't calling
And In above code an error occurred Uncaught TypeError: okAction is not a function.
Please suggest me I should I do for override confirm box.
Since the custom implementation is not a blocking call, you need to call it like
confirm('Do you want to remove this assessment', function (result) {
if (result) {
//something
} else {
//something
}
})
window.confirm = function (data, title, callback) {
if (typeof title == 'function') {
callback = title;
title = '';
}
swal({
title: title,
text: data,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
}, function (isConfirm) {
callback(isConfirm);
});
// return proxied.apply(this, arguments);
};