简体   繁体   中英

Using sweet alert for confirmation of deletion record

How do I transfer form this correct into using sweet alert.

I use this function site wide and would be nice to use sweetalert2 instead of the generic javascript alert.

https://sweetalert2.github.io/

jQueryAjaxDelete = form => {     
 if (confirm('Are you sure to delete this record ?')) {
    try {
        $.ajax({
            type: 'POST',
            url: form.action,
            data: new FormData(form),
            contentType: false,
            processData: false,
            success: function (res) {
                $('#view-all').html(res.html);
            },
            error: function (err) {
                console.log(err)
            }
        })
    } catch (ex) {
        console.log(ex)
    }
}

  //prevent default form submit event
  return false;
}

Thanks in advance

Make a new confirm prompt with Sweetalert and remove the vanilla js confirm prompt in your if condition. If confirm is true, then make the delete ajax call.

See code below

jQueryAjaxDelete = form => {
  // Modify as you wish
  const sweetOptions = {
    title: "Delete",
    text: "Are you sure  you want to delete this record?",
    type: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes!",
    cancelButtonText: "Cancel!",
    closeOnConfirm: false,
    closeOnCancel: false 
  }
  
  swal(sweetOptions, (isConfirmed) => {
    if (isConfirmed) {
      $.ajax({
          type: 'POST',
          url: form.action,
          data: new FormData(form),
          contentType: false,
          processData: false,
          success: function (res) {
              $('#view-all').html(res.html);
              
              // Fire a delete alert with SweetAlert here
              swal("Deleted!", "Deleted!", "success");
          },
          error: function (err) {
              console.log(err)
              swal("Cancelled", "Delete failed", "error");
          }
      })
    } else {
        swal("Cancelled", "Delete cancelled", "error");
    }
  }
   //prevent default form submit event
   return false;
 }
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM