Search code examples
ajaxdynamicqueuesweetalertsweetalert2

SweetAlert2 - Dynamic queue without clicking confirm button?


I am using the latest version of the jQuery plugin SweetAlert2. I want to use the "Dynamic queue"-function to make a AJAX call. So on the homepage there is a nice example, but you have to click a confirm button first to execute the AJAX call. I do not want this, when the alert is shown the AJAX call should execute immediately, without clicking a button. So how to do this?

Here the example from the homepage

swal.queue
([{
    title: 'Your public IP',
    confirmButtonText: 'Show my public IP',
    text: 'Your public IP will be received via AJAX request',
    showLoaderOnConfirm: true,
    preConfirm: function()
    {
        return new Promise(function (resolve)
        {
            $.get('https://api.ipify.org?format=json').done(function(data)
            {
                swal.insertQueueStep(data.ip);
                resolve();
            });
        });
    }
}])

Solution

  • You should pass the callback with the AJAX request to onOpen parameter:

    Swal.queue([{
      title: 'Your public IP',
      confirmButtonText: 'Show my public IP',
      text:
        'Your public IP will be received ' +
        'via AJAX request',
      onOpen: () => {
        fetch('https://api.ipify.org?format=json')
          .then(response => response.json())
          .then(data => {
            Swal.insertQueueStep(data.ip)
          })
      }
    }])
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>