lingo
lingo

Reputation: 1908

SweetAlert confirm with Ajax request

I'm new at Javascript - coding it actually for the first time. I'm trying to do a button with delete confirmation with SweetAlert. Nothing happens when I press the button with onclick="confirmDelete()". This code may be just crab, but here it is:

<script type="text/javascript">
    function confirmDelete() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        )},
            $.ajax({
                url: "scriptDelete.php",
                type: "POST",
                data: {id: 5},
                dataType: "html",
                success: function () {
                    swal("Done!","It was succesfully deleted!","success");
                }
            });
    }
</script>

<a href="#" onclick="confirmDelete()">Delete</a>

Can I add any alert if deleting fails?

Upvotes: 9

Views: 102186

Answers (5)

HIMANSHU GOHIL
HIMANSHU GOHIL

Reputation: 1

   $("#customerDatatable").on('click', '.Edit', function () {
        //var confirmMessageBox = confirm('Are you sure you wish to delete this job ?');
        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '/api/DairyWorkApi/DeleteClient?Id=' + this.id,
                    type: "Delete",
                    data: {'Id': this.id},
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function () {
                        Swal.fire(
                            'Deleted!',
                            'Your file has been deleted.',
                            'success'
                        ).then(function () {
                            location.reload();
                        });  
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        Swal.fire(
                            'Cancelled',
                            'Delete Is Failed',
                            'error'
                        );
                    }
                });

            }
        });
        //console.log(this.id);
    });`enter code here`

Upvotes: 0

Faisal
Faisal

Reputation: 4765

Try This Code.It's Working fine for me.

$('.delete-confirm').on('click', function() {
    var postID = $(this).val();
    console.log(postID);
    swal({
        title: "Are you sure?",
        text: "If you delete this post all associated comments also deleted permanently.",
        type: "warning",
        showCancelButton: true,
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes, delete it!",
    }, function() {
        setTimeout(function() {
            $.post("delete.php", {
                    id: postID
                },
                function(data, status) {
                    swal({
                            title: "Deleted!",
                            text: "Your post has been deleted.",
                            type: "success"
                        },
                        function() {
                            location.reload();
                        }
                    );
                }
            );

        }, 50);
    });
});

Upvotes: 7

Kevin
Kevin

Reputation: 21

I finally got this to work for that one dude 3 years from now.

function dropConfig(config_index){

  swal({
   title: "WARNING:", 
   text: "Are you sure you want to delete this connection?", 
   type: "warning",
   inputType: "submit",
   showCancelButton: true,
   closeOnConfirm: true,
   timer: 2000
       }, //end swal   }


function(isConfirm) {
      if (isConfirm == true) {

         //do the ajax stuff.
         $.ajax({
            method: "POST",
            url: "/drop_config",
            data: {"curr_config":  $("#curr_conf_conn_name_" + config_index).val()}})
           .success(function(msg) {
           show_notification(msg,"success");
           setInterval(function() {.reload();
           }, 2500);})
           .error(function(msg) {show_notification(msg.responseText,"danger");});




      } // end if }
   }); //  end function } & end swal )
}     //   end function }

Upvotes: 2

Dhiraj
Dhiraj

Reputation: 33618

If I understand your question correctly, you are asking how to handle error condition in ajax request. Ajax settings has an error attribute and it can be used like this

$.ajax({
  .... other settings you already have
  error: function (xhr, ajaxOptions, thrownError) {
    swal("Error deleting!", "Please try again", "error");
  }
});

Also, you are invoking swal in a wrong way. Swal has a callback like this

swal({settings}, function(isConfirm){});

Overall code would look something like this

function confirmDelete() {
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    }, function (isConfirm) {
        if (!isConfirm) return;
        $.ajax({
            url: "scriptDelete.php",
            type: "POST",
            data: {
                id: 5
            },
            dataType: "html",
            success: function () {
                swal("Done!", "It was succesfully deleted!", "success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                swal("Error deleting!", "Please try again", "error");
            }
        });
    });
}

Here is a demo http://jsfiddle.net/dhirajbodicherla/xe096w10/33/

Upvotes: 16

Bhavin Solanki
Bhavin Solanki

Reputation: 4818

You have doing mistake in swal({)} it should be swal({})

Updated code :

<script type="text/javascript">
    function confirmDelete() {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        },
         function(isConfirm){
           if (isConfirm) {
            $.ajax({
                url: "scriptDelete.php",
                type: "POST",
                data: {id: 5},
                dataType: "html",
                success: function () {
                    swal("Done!","It was succesfully deleted!","success");
                }
            });
          }else{
                swal("Cancelled", "Your imaginary file is safe :)", "error");
          } 
       })
    }
</script>

Upvotes: 3

Related Questions