Piet Piet - 14 days ago 7
Ajax Question

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();
});
});
}
}])

Answer

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: function () {
    $.get('https://api.ipify.org?format=json')
      .done(function (data) {
        swal.insertQueueStep(data.ip)
      })
  }
}])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/sweetalert2/latest/sweetalert2.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/sweetalert2/latest/sweetalert2.js"></script>