saintadjie
saintadjie

Reputation: 46

How to make Sweet alert auto close after ajax complete?

I'm using sweet alert, but i want make it close automatically if the request of ajax is completed

swal({
  title: "Are you sure?",
  text: "You are choosing order by custom search",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Confirm",
  closeOnConfirm: false,
  timer: **AUTO WITH AJAX??**
},

I am adding a variable

var dones = $(document).ajaxComplete(function(){
                            swal.close()
                        });

and make swal like this

swal({
  title: "Are you sure?",
  text: "You are choosing order by custom search",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Confirm",
  **timer: dones,**
  closeOnConfirm: false
},

but still not like I expected

Upvotes: 1

Views: 10589

Answers (3)

Arman H
Arman H

Reputation: 1754

for me I always do like that.I hope someone will get help :).

      <script>
       Swal.showLoading()
        jQuery.ajax({
            url: ajax_obj.ajax_url,
            type: "POST",
            data: {
                action: "your_action",
                security: ajax_obj.nonce,
                form_data: eiFormData
            },
            success: function (response) {
                swal.close()
            }
        })
      </script>

Upvotes: 0

Merrin K
Merrin K

Reputation: 1790

After ajax success function just trigger a time out function

setTimeout(function () {
    Swal.close()
}, 1000)

Upvotes: 0

Limon Monte
Limon Monte

Reputation: 54409

I recommend you to use SweetAlert2 - the supported fork of original SweetAlert.

What you looking for is onOpen parameter and .showLoading() method, here's your task:

Swal.fire({
  title: 'I will close automatically when AJAX request is finished',
  didOpen: function () {
    Swal.showLoading()
    // AJAX request simulated with setTimeout
    setTimeout(function () {
      Swal.close()
    }, 2000)
  }
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

PS. notice that SweetAlert2 is a little bit different from SweetAlert, check the simple migration guide: https://github.com/sweetalert2/sweetalert2/wiki/Migration-from-SweetAlert-to-SweetAlert2

Upvotes: 7

Related Questions