6

How can you use sweetalert to do an Ajax call without a confirm button but still show a loading gif? Basically I want a loading gif to display while the Ajax call is running. The out-of-the-box solution requires you to enable the confirm button before the Ajax call is made.

The following obviously doesn't work:

window.swal({
    title: "Checking...",
    text: "Please wait",
    imageUrl: "images/ajaxloader.gif",
    showConfirmButton: false,
    allowOutsideClick: false
},
function () {
    $.getJSON('myurl').done(function (data) {
        swal("", "Good job!", "success");
    }).fail(function (jqXHR, textStatus, err) {
        swal("", "An error occurred",    "error");
    });
});
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
adam78
  • 9,668
  • 24
  • 96
  • 207

3 Answers3

7

You don't need to do anything special. Just make your ajax call after you display swal, and call swal again when your ajax is completed.

window.swal({
  title: "Checking...",
  text: "Please wait",
  imageUrl: "images/ajaxloader.gif",
  showConfirmButton: false,
  allowOutsideClick: false
});

//using setTimeout to simulate ajax request
setTimeout(() => {
  window.swal({
    title: "Finished!",
    showConfirmButton: false,
    timer: 1000
  });
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" />
Ozan
  • 3,709
  • 2
  • 18
  • 23
0

Implementation example based on Ozan's very helpful answer:

Using vue-sweetalert2, VueJS 2, and Axios, and built in loader animation:

  let self = this;
  this.$swal.fire({
    title: "Processing Request...",
    text: "Please wait",
    onBeforeOpen() {
      self.$swal.showLoading(); //Adds built in loader animation during modal open
    },
    onAfterClose() {
      self.$swal.hideLoading(); //might not be necessary
    },
    allowOutsideClick: false, //makes modal behave captively
    allowEscapeKey: false,
    allowEnterKey: false
  });

  axios
    .post(`/api/myapi`, {"fake": "fake"})
    .then(r => {
      this.$swal.update({
        title: "Finished",
        html: `Response data: ${r.data}`
      });
      this.$swal.hideLoading(); //Disables loader spinner, enables button
    })
    .catch(err => {
      this.$swal.update({
        title: "FAILED!",
        text: "Something went wrong - either try again or contact support."
      });
      this.$swal.showValidationMessage(`Request failed: ${err}`);
      this.$swal.hideLoading(); //Disables loader spinner, enables button
    })
PotatoFarmer
  • 2,755
  • 2
  • 16
  • 26
0

With the help of PotatoFarmer's answer, I came up with a solution.

The modal is closed when the result is ready.

// create a 'Swal' variable
const WaitingModal = Swal.fire({
    icon: 'info',
    title: 'Fetching...',
    showConfirmButton: false,
    allowOutsideClick: false,
    
    // show loading on open
    didOpen: ()  => {
        Swal.showLoading();
    }
});

const url = '//api.github.com/users/benjamintemitope';

fetch(url)
.then(response => {
    if (!response.ok) {
      throw new Error(response.statusText)
    }
    return response.json();
})
.catch(error => {
    Swal.showValidationMessage(
      `Request failed: ${error}`
    )
    WaitingModal.hideLoading(); // hide loading
})
.then((result) => {
    console.log(result); // output

    WaitingModal.hideLoading();

    WaitingModal.close(); // close Swal Modal
})
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>