Search code examples
javascriptjquerysweetalert2

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


Solution

  • 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;
     }