Search code examples
javascriptajaxsweetalertsweetalert2

Wait for all ajax calls to end before showing SweetAlert2 Toastr mixin


I am using the code below to show a notification after an ajax request


const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });

//ajax call
$.ajax({
    .....
    success: function(response){
        reloadpanel1(response.id);   //another ajax call
        reloadpanel2(response.id);   //another ajax call
        Toast.fire({
            type: 'success',
            title: response.message,
            customClass: { popup: 'adjust' }
        })
    }
})

The problem is that the notification pops up even before reloadpanel1 and reloadpanel2 finish their requests. Is there a way where the Toastr won't fire if all ajax calls are not yet finished?

EDIT:

$(document).ajaxStart()/.ajaxStop() will not do since the notification message depends on the json response.message value


Solution

  • Found a neat solution for my problem using the jquery when function

    const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
    
    //ajax call
    $.ajax({
        .....
        success: function(response){
            $.when(reloadpanel1(), reloadpanel2()).done(function(){
                Toast.fire({
                   type: 'success',
                   title: response.message,
                   customClass: { popup: 'adjust' }
                })
            })
        }
    })