t4t5 / sweetalert

A beautiful replacement for JavaScript's "alert"
https://sweetalert.js.org
MIT License
22.4k stars 2.84k forks source link

Launch ajax requests at the opening of an alert #853

Closed r-hede closed 6 years ago

r-hede commented 6 years ago

Hi,

I am trying to launch multiple ajax requests (with async false) after opening an alert.

At first, I had the following code:

swal({
    text: "...",
    button: false,
    closeOnClickOutside: false
});

$(":checkbox:checked").each(function () {
    $.ajax({
        url: "/markasimportant/"+$(this).prop('id'),
        async: false
    });
});

location.reload();

This code is used to mark as important all of the checked items.

Using the parameter async to false, the alert is showing only when the requests is completed.

Then I tried the following code but it forces the user to click on a button.

swal(
{
    text: '...',
    button: {
        text: "...",
        closeModal: false
    },
    closeOnClickOutside: false
})
.then(name => {
    $(":checkbox:checked").each(function () {
        $.ajax({
            url: "/markasimportant/"+$(this).prop('id'),
            async: false
        });
    });
    location.reload();
});

Do you know how can I launch an ajax request at the opening of an alert without to force the user to click on a button?

Thank you.

r-hede commented 6 years ago

I finally found a solution.

I used a queue system with jQuery.

Here is the code:

swal({
    icon: "success",
    text: "Loading...",
    button: false,
    closeOnClickOutside: false,
    closeOnEsc: false
});

var functions = new Array();

$(":checkbox:checked").each(function () {
    functions.push(
        $.ajax({
            url: "/markasimportant/"+$(this).prop('id')
        })
    );
});

$.when.apply(null, functions).done(function() {
    location.reload();
});