how to close sweet alert on ajax request completion

Viewed 106950

I am using Sweet-alert in my angular app.

function GetDataFromServer(url) {
        SweetAlert.swal(
    {
        title: "",
        text: "Please wait.",
        imageUrl: "../../app/app-img/loading_spinner.gif",
        showConfirmButton: false
    });
        return $http.get(url)
        .then(success)
        .catch(exception);
        function success(response) {
            //SweetAlert.swal(
            //  {
            //      title: "",
            //      text: "data loaded",
            //  });
            return response.data;
        }
        function exception(ex) {
            return (ex);
        }

    }

Req #1 (Main Objective of my this post)

What I am looking for is when the ajax request completes i.e., controls enters in the then(), Sweet alert should automatically hide.

Req #2 Also while request processing, I don't want to have the Close pop-up button (Ok button) in the sweet alert.

enter image description here As per the documentation,showConfirmButton: false should hide it but it's not.

Any help/suggestion highly appreciated.
Thanks.

8 Answers

You can close current showing sweetalert by using below line of code anywhere you want.

swal.close();

That's it!

If you use swal2 you can close it using Swal.close() from anywhere inside your code for closing it when ajax is complete I think the code below is an easy way:

$(document).ajaxComplete(function () {
        Swal.close();
});

swal does not work with sync function (ex. get), you need make call get async

swal({
    type: 'warning',
    text: 'Please wait.',
    showCancelButton: false,
    confirmButtonText: "ok",
    allowOutsideClick: false,
    allowEscapeKey: false
}).then(function (result) {
    if (result) {

        setTimeout(function () {
            $http.get(url)
        }, 500);
    }
});

if you are using the AngularJS library known as angular-sweetalert then use swal.close(); to close the alert window. angular-sweetalert is a wrapper on the core sweetalert library package.

Cache the swal() to trigger it later.

function GetDataFromServer(url) {

let swalAlert = SweetAlert.swal; // cache your swal

swalAlert({
    title: "",
    text: "Please wait.",
    imageUrl: "../../app/app-img/loading_spinner.gif",
    showConfirmButton: false
});
return $http.get(url)
.then(success)
.catch(exception);
    function success(response) {
        swalAlert.close(); // this is what actually allows the close() to work
        return response.data;
    }
    function exception(ex) {
        return (ex);
    }

}
Related