Search code examples
javascriptjquerysweetalertsweetalert2

How to make AJAX call using SweetAlert


Am using SweetAlert to do an AJAX call when user want to delete an account.But isn't working below is my code. I want to also add confirm and cancel button but I don't know how to use SweetAlert very well.

Any help will be appreciated.

I'm using CDN of SweetAlert.

https://unpkg.com/sweetalert/dist/sweetalert.min.js from https://sweetalert.js.org/

 swal({
   closeOnClickOutside: false,
   icon: "warning",
   title: 'Do you want to remove your account?',
   text: 'This action can not be undo',
   showConfirmButton: false,
   closeOnConfirm: false,
   showSpinner: true
 },function () {
   $.ajax({
     url: "delete_account.php",
     method: "POST",
     data: {
       id: 5
     },
     success: function () {
       swal("Deleted!", "Successfully deleted", "success");
     }
   });
 });

Solution

  • You can call ajax on the confirmation of sweet alert as follows.

    swal({
        title: "Are you sure to delete this  of ?",
        text: "Delete Confirmation?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Delete",
        closeOnConfirm: false
      },
      function() {
        $.ajax({
            type: "post",
            url: "url",
            data: "data",
            success: function(data) {}
          })
          .done(function(data) {
            swal("Deleted!", "Data successfully Deleted!", "success");
          })
          .error(function(data) {
            swal("Oops", "We couldn't connect to the server!", "error");
          });
      }
    );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.3.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">