0

I want to add timer after callback another function in Sweetalert2. In the example just add timer when swal run.

this is basic code :

swal({
  title: 'alert!',
  text: 'I need this close after my function',
})

and below is ajax and I need the swal close in second after ajax success

$.ajax({
    dataType: "json",
    url: url,
    type: "GET",
    data: {some: data},
    success: function (json) {
        if (json.status === 'OK') {
            swal({
                timer:2000
            });
        }
    }
});

but when ajax success, new modal of swal() opened with timer, not close the current swal()

Limon Monte
  • 52,539
  • 45
  • 182
  • 213
totoprayogo1916
  • 160
  • 4
  • 20

2 Answers2

0

To hide current modal on ajax success. Try this

$.ajax({
dataType: "json",
url: url,
type: "GET",
data: {some: data},
success: function (json) {
    if (json.status === 'OK') {
        hideSwal()
    }
}});
function hideSwal(){
setTimeout(function(){
  var button = document.getElementsByClassName('swal2-confirm')[0]
  button.click()
},2000)
}

setTimeout(function(){
  var button = document.getElementsByClassName('swal2-confirm')[0]
  button.click()
},2000)
swal('Any fool can use a computer')
<script src="https://cdn.jsdelivr.net/sweetalert2/6.6.0/sweetalert2.min.js"></script>
Gaurav Chaudhary
  • 1,491
  • 13
  • 28
0

This is inpired by answer From Gaurav Chaudhary. Id modified with standard of swal doc. I publish this because he not accept my edit.

//if(swal.isVisible()) { // uncomment to check if modal swal visible
    setTimeout(function(){
        swal.closeModal();
     }, 2000);
//}


swal('Any fool can use a computer')
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/sweetalert2/6.6.0/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/sweetalert2/6.6.0/sweetalert2.min.js"></script>
totoprayogo1916
  • 160
  • 4
  • 20