How to redirect page after click on Ok button on sweet alert?
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>';
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. ð