Javascript - Uncaught (in promise) - javascript

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

Related

Add loading to sweetalert when send request to livewire

I wrote my code below and it works correctly and the answer is received correctly. But the problem is that when the confirm button is clicked, the sweetalert closes
I want the sweetalert not to be closed until the request is fully executed and the loading button to be displayed. I saw a lot of questions about this but they were related to ajax and I could not create them for livewire
document.addEventListener('DOMContentLoaded', function () {
$('.eg-swal-av3').on("click", function (e) {
Swal.fire({
title: 'title',
text: "content",
icon: 'info',
showCancelButton: true,
confirmButtonText: 'بله ایجاد کن',
cancelButtonText : 'لغو',
}).then(function (result) {
if (result.value) {
#this.call('createRequest');
}
});
e.preventDefault();
});
});
You're looking for the preConfirm property, which accepts a callback. This is where you would run the call to your createRequest.
I would also add a allowOutsideClick to be true when loading, so that the alert is visible throughout the request.
Swal.fire({
title: 'title',
text: "content",
icon: 'info',
showCancelButton: true,
confirmButtonText: 'بله ایجاد کن',
cancelButtonText : 'لغو',
allowOutsideClick: () => !Swal.isLoading(),
preConfirm: function(result) {
if (result) {
return #this.call('createRequest').then(() => {
Swal.fire('Loading complete');
});
}
},
});

How to Redirect user after Submit button with sweet alert [duplicate]

I am able to display sweet alert after the page refresh but I have to click on Ok button which I am getting on sweet alert to redirect the page.Please help me in this.
<?php
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("WOW!","Message!","success");';
echo '}, 1000);'
echo 'window.location.href = "index.php";';
echo '</script>';
?>
Just make use of JavaScript promises. Put the then method after swal function. We do not need to use timer features.
For example:
swal({
title: "Wow!",
text: "Message!",
type: "success"
}).then(function() {
window.location = "redirectURL";
});
The promise method .then is used to wait until the user reads the information of modal window and decide which decision to make by clicking in one button. For example, Yes or No.
After the click, the Sweet Alert could redirect the user to another screen, call another Sweet Alert modal window with contains new and subsequent question, go to a external link, etc.
Again, we do not have to use timer because it is much better to control user action. The user could wait for the eternity or take action as a Thanos' or Iron Man's finger snap. 😜
With the use of promises, the code becomes shorter, clean and elegant. 😉
To specify a callback function, you have to use an object as the first argument, and the callback function as the second argument.
echo '<script>
setTimeout(function() {
swal({
title: "Wow!",
text: "Message!",
type: "success"
}, function() {
window.location = "redirectURL";
});
}, 1000);
</script>';
You can use the build-in function timer, i.e.:
swal({
title: "Success!",
text: "Redirecting in 2 seconds.",
type: "success",
timer: 2000,
showConfirmButton: false
}, function(){
window.location.href = "//stackoverflow.com/a/37358578/797495";
});
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
Best and Simple solution, we can add more events as well!
swal({ title: "WOW!",
text: "Message!",
type: "success"}).then(okay => {
if (okay) {
window.location.href = "URL";
}
});
I wasn't able to do that with any swal(sweatAlert) default callback function, so I forced with jquery, got the Ok button class inspecting the element in chrome an made something like this:
<script>
sweetAlert({
title:'Warning!',
text: 'Invalid user or password!',
type:'warning'
},function(isConfirm){
alert('ok');
});
$('.swal2-confirm').click(function(){
window.location.href = 'index.php';
});
</script>
The 'Ok' alert in function(isConfirm) was just a test to see if it would get into this function, if so I should be able to redirect from there, but I wasn't...
So I used jQuery to determine if the button "OK" of swal was clicked by getting it class: ".swal2-confirm' then I could redirect with success...
Hope this helps you all !
PS: I am using php echo to run the script, I din't have to leave php to run it, just use single quotes and you're done !
If anyone needs help, this code is working!
swal({
title: 'Request Delivered',
text: 'You can continue with your search.',
type: 'success'
}).then(function() {
window.location.href = "index2.php";
})
Swal.fire({
title: result.value.title,
icon: result.value.icon,
text: result.value.message,
}).then(function() {
window.location.href = "url";
})
None of the above solutions worked for me, I had to use .then
swal({
title: 'Success!',
text: message,
type: 'success',
confirmButtonText: 'OK'
}).then(() => {
console.log('triggered redirect here');
});
I think this will help. It's same as given by Mr. Barmer. But I have enclosed this within php tags.
Here it goes....
<?php if(!empty($_GET['submitted'])):?>
<script>
setTimeout(function() {
swal({
title: "Congratulaions!",
text: "Signed up successfully, now verify your mail",
type: "success",
confirmButtonText: "Ok"
}, function() {
window.location = "index.php";
}, 1000);
});
</script>
<?php endif;?>
function confirmDetete(ctl, event) {
debugger;
event.preventDefault();
var defaultAction = $(ctl).prop("href");
swal({
title: "Are you sure?",
text: "You will be able to add it back again!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "Cancel",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
$.get(ctl);
swal({
title: "success",
text: "Deleted",
confirmButtonText: "ok",
allowOutsideClick: "true"
}, function () { window.location.href = ctl })
// $("#signupform").submit();
} else {
swal("Cancelled", "Is safe :)", "success");
}
});
}
Existing answers did not work for me i just used $('.confirm').hide(). and it worked for me.
success: function(res) {
$('.confirm').hide()
swal("Deleted!", "Successfully deleted", "success")
setTimeout(function(){
window.location = res.redirect_url;
},700);
I did it by using this code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
<script>
$(".confirm").on('click',function(){
window.location.href = "index.php";
});
</script>
Thanks.
setTimeout(function(){
Swal.fire({
title: '<span style="color:#fff">Kindly click the link below</span>',
width: 600,
showConfirmButton: true,
confirmButtonColor: '#ec008c',
confirmButtonText:'<span onclick="my2()">Register</span>',
padding: '3em',
timer: 10000,
background: '#fff url(bg.jpg)',
backdrop: `
rgba(0,0,123,0.4)
center left
no-repeat
`
})
}, 1500);
}
function my2() {
window.location.href = "https://www.url.com/";
}
Worked for me!!
<head>
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
</head>
<?php
echo "<script>
Swal.fire({
title: 'Do you want to save the changes?',
showCancelButton: true,
confirmButtonText: `Save`,
denyButtonText: `Don't save`,
}).then((result) => {
if (result.isConfirmed) {
window.location = 'www.google.com';
} else if (result.isDenied) {
Swal.fire('Changes are not saved', '', 'info')
}
})
</script>";
?>
You can use callback function in SweetAlert2, it worked for me.
swal({
title: "Success!",
text: "Example success message",
type: "success"
}, function() {
window.location.href = 'https://some-url';
});
$('.delete-record').on('click', function (e) {
e.preventDefault();
window.url = $(this).attr('href');
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Confirm',
padding: '2em'
}).then(function (result) {
if (result.value) {
console.log(window.url);
window.location.href = window.url;
}
});
});
swal("Payment send successfully", "Thanks for using Npay!", "success")
.then(function() {
router.push("/")
});

Vue.js call method on service in component

I've made a component in Vue.js 2.0 that delete's things with sweetalert. It looks like this:
export default {
props:['service', 'method', 'id'],
methods: {
destroy() {
swal({
title: 'Weet u het zeker?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja verwijder',
cancelButtonText: 'Stop!',
confirmButtonColor: '#34495e',
cancelButtonColor: '#ff3860',
}).then (() => {
this.service[this.method](this.id)
.then(() => {
swal({
title: 'Verwijderd',
text: 'Succesvol verwijderd',
type: 'success',
showConfirmButton: false,
timer: 2000
});
location.reload();
})
.catch(() => {
swal({
title: 'Fout',
text: 'Heeft u voldoende rechten?',
type: 'error',
showConfirmButton: false,
timer: 2000
});
});
})
}
}
}
The problem is that this:
this.service[this.method](this.id)
Is not working. I'm passing the props like this:
<destroy :service="Service" method="destroy" :id="relation.id"></destroy>
The destroy method in the service class looks like this:
destroy(id) {
return axios.delete('/relaties/' + id);
}
In my vue debug bar the destroy component looks like this:
The error in my console:
Uncaught (in promise) TypeError: Cannot read property 'then' of undefined
at eval (eval at ./node_modules/babel-loader/lib/index.js?{"cacheDirectory":true,"presets":[["env",{"modules":false,"targets":{"browsers":["> 2%"],"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/components/shared/Destroy.vue (app.js?id=d89bceb…:319), <anonymous>:27:54)
at <anonymous>
Any idea how I could fix this?
export default {
props:['service', 'method', 'id'],
methods: {
destroy() {
var self = this;
swal({
title: 'Weet u het zeker?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja verwijder',
cancelButtonText: 'Stop!',
confirmButtonColor: '#34495e',
cancelButtonColor: '#ff3860',
}).then (() => {
self.service[self.method](self.id)
.then(() => {
swal({
title: 'Verwijderd',
text: 'Succesvol verwijderd',
type: 'success',
showConfirmButton: false,
timer: 2000
});
location.reload();
})
.catch(() => {
swal({
title: 'Fout',
text: 'Heeft u voldoende rechten?',
type: 'error',
showConfirmButton: false,
timer: 2000
});
});
})
}
}
}
You should create global link to "this" variable, in SWAL callback function "this" is replaced by local SWAL var.

Error when use jQuery sweetalert2

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

How to redirect page after click on Ok button on sweet alert?

I am able to display sweet alert after the page refresh but I have to click on Ok button which I am getting on sweet alert to redirect the page.Please help me in this.
<?php
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("WOW!","Message!","success");';
echo '}, 1000);'
echo 'window.location.href = "index.php";';
echo '</script>';
?>
Just make use of JavaScript promises. Put the then method after swal function. We do not need to use timer features.
For example:
swal({
title: "Wow!",
text: "Message!",
type: "success"
}).then(function() {
window.location = "redirectURL";
});
The promise method .then is used to wait until the user reads the information of modal window and decide which decision to make by clicking in one button. For example, Yes or No.
After the click, the Sweet Alert could redirect the user to another screen, call another Sweet Alert modal window with contains new and subsequent question, go to a external link, etc.
Again, we do not have to use timer because it is much better to control user action. The user could wait for the eternity or take action as a Thanos' or Iron Man's finger snap. 😜
With the use of promises, the code becomes shorter, clean and elegant. 😉
To specify a callback function, you have to use an object as the first argument, and the callback function as the second argument.
echo '<script>
setTimeout(function() {
swal({
title: "Wow!",
text: "Message!",
type: "success"
}, function() {
window.location = "redirectURL";
});
}, 1000);
</script>';
You can use the build-in function timer, i.e.:
swal({
title: "Success!",
text: "Redirecting in 2 seconds.",
type: "success",
timer: 2000,
showConfirmButton: false
}, function(){
window.location.href = "//stackoverflow.com/a/37358578/797495";
});
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
Best and Simple solution, we can add more events as well!
swal({ title: "WOW!",
text: "Message!",
type: "success"}).then(okay => {
if (okay) {
window.location.href = "URL";
}
});
I wasn't able to do that with any swal(sweatAlert) default callback function, so I forced with jquery, got the Ok button class inspecting the element in chrome an made something like this:
<script>
sweetAlert({
title:'Warning!',
text: 'Invalid user or password!',
type:'warning'
},function(isConfirm){
alert('ok');
});
$('.swal2-confirm').click(function(){
window.location.href = 'index.php';
});
</script>
The 'Ok' alert in function(isConfirm) was just a test to see if it would get into this function, if so I should be able to redirect from there, but I wasn't...
So I used jQuery to determine if the button "OK" of swal was clicked by getting it class: ".swal2-confirm' then I could redirect with success...
Hope this helps you all !
PS: I am using php echo to run the script, I din't have to leave php to run it, just use single quotes and you're done !
If anyone needs help, this code is working!
swal({
title: 'Request Delivered',
text: 'You can continue with your search.',
type: 'success'
}).then(function() {
window.location.href = "index2.php";
})
Swal.fire({
title: result.value.title,
icon: result.value.icon,
text: result.value.message,
}).then(function() {
window.location.href = "url";
})
None of the above solutions worked for me, I had to use .then
swal({
title: 'Success!',
text: message,
type: 'success',
confirmButtonText: 'OK'
}).then(() => {
console.log('triggered redirect here');
});
I think this will help. It's same as given by Mr. Barmer. But I have enclosed this within php tags.
Here it goes....
<?php if(!empty($_GET['submitted'])):?>
<script>
setTimeout(function() {
swal({
title: "Congratulaions!",
text: "Signed up successfully, now verify your mail",
type: "success",
confirmButtonText: "Ok"
}, function() {
window.location = "index.php";
}, 1000);
});
</script>
<?php endif;?>
function confirmDetete(ctl, event) {
debugger;
event.preventDefault();
var defaultAction = $(ctl).prop("href");
swal({
title: "Are you sure?",
text: "You will be able to add it back again!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "Cancel",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
$.get(ctl);
swal({
title: "success",
text: "Deleted",
confirmButtonText: "ok",
allowOutsideClick: "true"
}, function () { window.location.href = ctl })
// $("#signupform").submit();
} else {
swal("Cancelled", "Is safe :)", "success");
}
});
}
Existing answers did not work for me i just used $('.confirm').hide(). and it worked for me.
success: function(res) {
$('.confirm').hide()
swal("Deleted!", "Successfully deleted", "success")
setTimeout(function(){
window.location = res.redirect_url;
},700);
I did it by using this code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>
<script>
$(".confirm").on('click',function(){
window.location.href = "index.php";
});
</script>
Thanks.
setTimeout(function(){
Swal.fire({
title: '<span style="color:#fff">Kindly click the link below</span>',
width: 600,
showConfirmButton: true,
confirmButtonColor: '#ec008c',
confirmButtonText:'<span onclick="my2()">Register</span>',
padding: '3em',
timer: 10000,
background: '#fff url(bg.jpg)',
backdrop: `
rgba(0,0,123,0.4)
center left
no-repeat
`
})
}, 1500);
}
function my2() {
window.location.href = "https://www.url.com/";
}
Worked for me!!
<head>
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
</head>
<?php
echo "<script>
Swal.fire({
title: 'Do you want to save the changes?',
showCancelButton: true,
confirmButtonText: `Save`,
denyButtonText: `Don't save`,
}).then((result) => {
if (result.isConfirmed) {
window.location = 'www.google.com';
} else if (result.isDenied) {
Swal.fire('Changes are not saved', '', 'info')
}
})
</script>";
?>
You can use callback function in SweetAlert2, it worked for me.
swal({
title: "Success!",
text: "Example success message",
type: "success"
}, function() {
window.location.href = 'https://some-url';
});
$('.delete-record').on('click', function (e) {
e.preventDefault();
window.url = $(this).attr('href');
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Confirm',
padding: '2em'
}).then(function (result) {
if (result.value) {
console.log(window.url);
window.location.href = window.url;
}
});
});
swal("Payment send successfully", "Thanks for using Npay!", "success")
.then(function() {
router.push("/")
});

Categories

Resources