[javascript] 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>';
?>

This question is related to javascript jquery sweetalert

The answer is


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

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

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 !


_x000D_
_x000D_
setTimeout(function () { _x000D_
swal({_x000D_
  title: "Wow!",_x000D_
  text: "Message!",_x000D_
  type: "success",_x000D_
  confirmButtonText: "OK"_x000D_
},_x000D_
function(isConfirm){_x000D_
  if (isConfirm) {_x000D_
    window.location.href = "//stackoverflow.com";_x000D_
  }_x000D_
}); }, 1000);
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
_x000D_
_x000D_


Or you can use the build-in function timer, i.e.:

_x000D_
_x000D_
swal({_x000D_
  title: "Success!",_x000D_
  text: "Redirecting in 2 seconds.",_x000D_
  type: "success",_x000D_
  timer: 2000,_x000D_
  showConfirmButton: false_x000D_
}, function(){_x000D_
      window.location.href = "//stackoverflow.com";_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
_x000D_
_x000D_


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");

            }
        });
}

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 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.


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

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

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.


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