5

How can I display loading icon or spin while my during ajax call. below is my code

 swal({
       title: "Confirm your transaction",
        html:true,
       showSpinner: true,
       showCancelButton: true,
        confirmButtonColor: "#DD6B55",
       confirmButtonText: "Send",
      closeOnConfirm: false
  },function () {
      $.ajax({
   type: "post",
    url: remoteUrl,
    data: largeParams,
   success: function (data) { }
  }).done(function (data) {
    swal("Thank you for your order", data, "success");
  }).error(function (data) {
  swal("Oops", "We couldn't connect to the server!", "error");
 });
});

Answers will be appreciated.

Iamgisnet
  • 171
  • 3
  • 3
  • 12
  • I've never used SweetAlert, but checking the webpage (https://sweetalert.js.org) I can´t find all this methods: html, showSpinner, showCancelButton, confirmButtonColor, confirmButtonText, closeOnConfirm... Are you using this plugin or is there another one? – A. Iglesias Sep 23 '17 at 06:46
  • using promises `https://sweetalert.js.org/guides/#using-promises` – tonoslfx Sep 23 '17 at 08:52

7 Answers7

7

This has worked best for me.

Previously, this was the case:

Rather than opening another sweet alert change the content within the sweet alert, otherwise there will be an ugly flash when the sweet alert is trying to change.

Thankfully this issue has been resolved in version 9.8.2.


Now that the previous issue has been resolved, we can open new sweet alert modals in our ajax call without that ugly flash.

You can also put a setTimeout around the swal.fire() to prevent an ugly transition between modals like so:

// this way when the ajax call completes quickly, the loader will still be shown for a bit
setTimeout(function() {
    swal.fire({
        icon: 'success',
        html: '<h5>Success!</h5>'
    });
}, 500);
// the loader html
var sweet_loader = '<div class="sweet_loader"><svg viewBox="0 0 140 140" width="140" height="140"><g class="outline"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="rgba(0,0,0,0.1)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></g><g class="circle"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="#71BBFF" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dashoffset="200" stroke-dasharray="300"></path></g></svg></div>';

$.ajax({
    type: 'POST',
    url:  myurl,
    data: str,
    // here
    beforeSend: function() {
        swal.fire({
            html: '<h5>Loading...</h5>',
            showConfirmButton: false,
            onRender: function() {
                 // there will only ever be one sweet alert open.
                 $('.swal2-content').prepend(sweet_loader);
            }
        });
    },
    success: function(json) {
        try {
            json = JSON.parse(json);
        }
        catch(error) {
            swal.fire({
                icon: 'error',
                html: '<h5>Error!</h5>'
            });
            return false;
        }
        if(json.success) {
            swal.fire({
                icon: 'success',
                html: '<h5>Success!</h5>'
            });
        } else {
            swal.fire({
                icon: 'error',
                html: '<h5>Error!</h5>'
            });
        }
    },
    error: function() {
        swal.fire({
            icon: 'error',
            html: '<h5>Error!</h5>'
        });
        return false;
    }
});

Check out this codepen for an example.

Apparently you can also use the following to show real time progress, but I have not tested it.

xhr: function() {
    var xhr = $.ajaxSettings.xhr();
    xhr.upload.onprogress = function(e) {
        // progressive loader
    };
    return xhr;
},
Souleste
  • 1,887
  • 1
  • 12
  • 39
  • This was very helpful for what I was trying to do, add an indeterminant spinner to a Sweet Alert 2 modal while I'm waiting for an AJAX call to return. However, if you're reading this, please look at the codepen code primarily, as the CSS class names are different than what the Souleste put in this comment. Thank you for the help! – Jared Schnelle Oct 06 '20 at 17:35
2

Use the promises, this code reference from the website.

https://sweetalert.js.org/guides/#ajax-requests

swal({
  text: 'Search for a movie. e.g. "La La Land".',
  content: "input",
  button: {
    text: "Search!",
    closeModal: false,
  },
})
.then(name => {
  if (!name) throw null;

  return fetch(`https://itunes.apple.com/search?term=${name}&entity=movie`);
})
.then(results => {
  return results.json();
})
.then(json => {
  const movie = json.results[0];

  if (!movie) {
    return swal("No movie was found!");
  }

  const name = movie.trackName;
  const imageURL = movie.artworkUrl100;

  swal({
    title: "Top result:",
    text: name,
    icon: imageURL,
  });
})
.catch(err => {
  if (err) {
    swal("Oh noes!", "The AJAX request failed!", "error");
  } else {
    swal.stopLoading();
    swal.close();
  }
});
tonoslfx
  • 3,422
  • 15
  • 65
  • 107
1

Simple example working with last Sweet Alert

$('#form_button_submit').click(function(){

            swal({
                title:"", 
                text:"Loading...",
                icon: "https://www.boasnotas.com/img/loading2.gif",
                buttons: false,      
                closeOnClickOutside: false,
                timer: 3000,
                //icon: "success"
            });
            

        });
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>



<button type="submit" id="form_button_submit">
        TEST LOAD
</button>
Max
  • 526
  • 6
  • 12
0
swal({
        title: "Are you sure?",
        text: "",
        confirmButtonClass: "show-loading-icon",
        cancelButtonClass: "show-loading-icon-delete",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        closeOnConfirm: false,
        showCancelButton: true,
        closeOnCancel: true,
        titleClass: "bluecolor",
    }, function (selection) {

        //If confirm click then show loading on confirm button
        if(selection){
            var initial = $(".show-loading-icon").html();

            // you can add glyphicon or font-awesome icon html codes
            $(".show-loading-icon").html("Loading...").attr("disabled", "disabled");

            //Do some operation, eg. ajax call, fetch request etc, then show icon again
            $(".show-loading-icon").html(initial).removeAttr("disabled");
        }
        else{

            //Similary for cancel also....
                    //.....

        }
    });
Vinod Selvin
  • 369
  • 2
  • 10
0

Sweetalert (version 1) has this built in, just make the button disabled and it will display a loading icon instead of your confirm text.

jQuery <1.9

$('.sa-button-container button').attr('disabled', true);

jQuery 1.9+

$('.sa-button-container button').prop('disabled', true);
Brummy
  • 183
  • 1
  • 11
0

Latest version 11

const waitingPopup = Swal.fire({
  title: "Waiting for response from server!",
  html: "please wait!<br>",
  allowOutsideClick: false,
  didOpen: () => {
    Swal.showLoading();
  },
});

if you want to close it

/// close from ajax or fetch
setTimeout(() => {
  waitingPopup.close(); // to close swal
}, 2000);
Hyzyr
  • 568
  • 4
  • 13
-1

From the GitHub doc:

swal({
  title: "Ajax request example",
  text: "Submit to run ajax request",
  type: "info",
  showCancelButton: true,
  closeOnConfirm: false,
  showLoaderOnConfirm: true
}, function () {
  setTimeout(function () {
    swal("Ajax request finished!");
  }, 2000);
});

I've tried this and works perfectly, just replace the setTimeout function with your ajax request.