FireFoxII FireFoxII - 10 days ago 14
Javascript Question

How to use confirm (then submit) using sweet alert?

I have a table where each row have a delete button with this form

<form id="tableDelete_1">
<input type="hidden" name="tipo" value="delete" />
<input type="submit" name="send" value="Delete" class="btn btn-danger btn-xs" onClick="return confirm(`Are you sure?`)" />
</form>

<form id="tableDelete_2">
<input type="hidden" name="tipo" value="delete" />
<input type="submit" name="send" value="Delete" class="btn btn-danger btn-xs" onClick="return confirm(`Are you sure?`)" />
</form>


Then this on bottom of the page

$(document).on('submit', '[id^=tableDelete_]' , function() {
return callAjax( $(this).serialize() );
});

function callAjax( data ) {
$.ajax({
type : 'POST',
url : 'call/page.php',
data : data,
success : function(data) { ... },
error: function(data) { ... }
});
return false;
};


Now I want to delete the classic

onClick="return confirm(`Are you sure?`)"


and use sweetalert...
I have problem just at start when I want to show only the popup with this function

$(document).on('submit', '[id^=tableDelete_]' , function() {
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(){
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
};


The popup is showed only for a second then the page is reloaded because I think the form is submitted...

Please give me help

Answer

If I read correctly, I think you're looking for something like this?

$(document).on('submit', '[id^=tableDelete_]', function (e) {
  e.preventDefault();

  var data = $(this).serialize();

  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!",
    cancelButtonText: "No, cancel plx!",
    closeOnConfirm: false,
    closeOnCancel: false
  },
    function (isConfirm) {
      if (isConfirm) {
        $.ajax({
          type: 'POST',
          url: 'call/page.php',
          data: data,
          success: function (data) {
            swal("Deleted!", "Your imaginary file has been deleted.", "success");
          },
          error: function (data) {
            swal("NOT Deleted!", "Something blew up.", "error");
          }
        });
      } else {
        swal("Cancelled", "Your imaginary file is safe :)", "error");
      }
    });

  return false;
});
Comments