40

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>';
?>
Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65

17 Answers17

83

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.

Alexandre Ribeiro
  • 1,384
  • 1
  • 13
  • 19
45

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>';
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you for reply Mr,Barmar, have you checked by code? I have to display that function in echo" " .Can you help me how write the code in echo. –  May 21 '16 at 05:17
  • There's no difference when you write it with `echo`. – Barmar May 21 '16 at 05:30
  • code is working perfectly without echo but when i am inserting en echo its not working –  May 21 '16 at 05:48
  • I have to load sweet alert on page refresh. My code is working on page refresh but that ok button is not working. –  May 21 '16 at 05:50
  • 1
    Sorry Mr.Barmar, code is not working.Page is totally blank. –  May 21 '16 at 06:56
  • Add an update to your question showing the full code. – Barmar May 21 '16 at 12:46
  • You're doing the redirect outside of the `swal()` function, so it doesn't wait for the user to respond. – Barmar May 24 '16 at 15:06
  • Please help me how to do that because i tried your code but it's not working. –  May 25 '16 at 06:18
  • What is it doing wrong? Is it displaying the alert? What happens after you click OK? Are there any errors in the Javascript console? – Barmar May 25 '16 at 14:28
  • Yes, Mr.Barmar. There were issue in my plugin.So i deleted and updated new one with your code and its working perfectly.I am really appreciate for you support and help. Thank you very much.You give me great solution. –  May 25 '16 at 17:15
  • Mr.Barmar, I have issue on sweetalert.Can you help me once again?http://stackoverflow.com/questions/39136597/how-to-use-sweetalert-to-display-variable-value-on-popup –  Aug 25 '16 at 04:32
  • Hello Mr.Barmar.One more issue in sweet alert.Please please help me in this..http://stackoverflow.com/questions/39754112/how-to-display-session-value-on-sweet-alert-popup/39754182?noredirect=1#comment66804612_39754182 –  Sep 28 '16 at 18:00
17

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

swal({
  title: "Success!",
  text: "Redirecting in 2 seconds.",
  type: "success",
  timer: 2000,
  showConfirmButton: false
}, function(){
      window.location.href = "//this-person-does-not-exist.com";
});
<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">
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Mr.Pedro, have you checked by code? I have to display that function in echo" " .Can you help me how write the code in echo. –  May 21 '16 at 05:28
7

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";
  }
});
Kapil Chhabra
  • 415
  • 5
  • 7
5

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 !

  • it's doesn't redirect – Freddy Sidauruk Sep 20 '16 at 08:13
  • Inspect the element with chrome, probably, if it's not redirecting, it will return an error on the console. Also remember to add the sweetalert(and jquery) script and CSS properly. – Felipe Pena Sep 21 '16 at 20:25
  • *Correction: I was using an older swal files, just update to the newest one and the function should work, as @PedroLobito explained bellow. – Felipe Pena Nov 08 '16 at 18:13
  • I looked everywhere and nothing suggested worked until I saw this post; worked like a charm. Thanks. Only if I can this darn thing to work in IE. Anyone knows why the callback function is not executed? – NoBullMan Mar 19 '17 at 17:23
5

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";
        })
3
                Swal.fire({
                    title: result.value.title,
                    icon: result.value.icon,
                    text: result.value.message,
                }).then(function() {
                    window.location.href = "url";
                })
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 23 '22 at 05:24
1

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');
});
Jagadesha NH
  • 2,529
  • 2
  • 23
  • 41
0

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;?>
mnis.p
  • 451
  • 4
  • 9
  • This doesn't qualify as a good answer as the question has been answered already, you should've edited @Barmer's answer and updated it with PHP tags. – Vignesh Apr 16 '18 at 12:53
  • 1
    yeah, you're right. I'm sorry. I'm not well acquainted with asking and responding on this site, it won't happen anymore and thanks for pointing this out. – mnis.p Jun 07 '18 at 20:37
0
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");

            }
        });
}
0

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);
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Chidananda Nayak
  • 1,161
  • 1
  • 13
  • 45
0

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.

Y. Joy Ch. Singha
  • 3,056
  • 24
  • 26
0
  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/";   
} 
0

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

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';
});
MyFRA
  • 366
  • 2
  • 5
0
  $('.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;
                }
            });
        });
Ayoub ait
  • 163
  • 2
  • 4
  • Please don't only share code, but also an explanation whats happening – Timberman Jan 11 '22 at 23:48
  • for example you have this a tag delete so when this a clicked you will stop the event and shwo the swal whith confermation button and cancel button if ok button clicked you will redirect the user to the link in href att – Ayoub ait Jan 13 '22 at 12:53
0
swal("Payment send successfully", "Thanks for using Npay!", "success")
.then(function() {
    router.push("/")
});

Shamaz saeed
  • 387
  • 3
  • 8