Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sweet Alert - Ajax call without confirm button

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");
    });
});
like image 682
adam78 Avatar asked Apr 13 '17 07:04

adam78


People also ask

How do you confirm with sweet alert?

SweetAlert uses promises to keep track of how the user interacts with the alert. If the user clicks the confirm button, the promise resolves to true . If the alert is dismissed (by clicking outside of it), the promise resolves to null . swal("Click on either the button or outside the modal.")

How to call sweet Alert?

Once the library is set up, creating a SweetAlert message is very easy. All you have to do is call the swal() function. swal("Here's a message!", " Have a nice day!")

What is Swal close?

swal. close(); --> Close the currently open SweetAlert programmatically. self. showProgress = function(message) { swal({ title: message }); swal. showLoading(); }; self.

How to use SweetAlert in html?

There are two ways to create a sweet alert using the Swal. fire() function. You can either pass the title, body text, and icon value in three different arguments, or you can pass a single argument as an object with different values as its key-value pairs.


1 Answers

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" />
like image 88
Ozan Avatar answered Nov 15 '22 13:11

Ozan