artisticre's avatar

SweetAlert Delete Confirm

Does anyone know how to get a delete confirm button to delete? My delete method works and deletes correctly but if I add the sweetalert to the delete button, it pops up are you sure you want to delete but doesn't delete anything. I am not sure how to add my method to the popup.

Scripts for Sweetalert

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script type="text/javascript">
    $(function() {
      $(document).on('click','#delete', function(e){
        e.preventDefault();
        var link = $(this).attr("href");

        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) {
Swal.fire(
  'Deleted!',
  'Your file has been deleted.',
  'success'
)
}
})

      });
    });


</script>

Link

<a href="{{ route('category.delete',$cat->id) }}" id="delete" class="btn btn-danger btn-sm" title="Delete {{$cat->category_name}}"><i class="fa fa-trash"></i></a>

Controller Method

public function CategoryDelete($id)
     {
        
        $category = Category::findOrFail($id);
        $img = public_path('backend/uploads/categories/'.$category->category_icon);
        unlink($img);
        
        Category::findOrFail($id)->delete();

        $notification = array(
            'message' => 'Category Deleted Successfully',
            'alert-type' =>'success'
        );

        return redirect()->route('all.categories')->with($notification);
     }
0 likes
1 reply
OussamaMater's avatar

Well makes sense, because you are not making any delete request, you need to update your code

if (result.isConfirmed) {
// add logic here if the user confirmed the delete
// an example would be
        $.ajax({
            url: // your route here with the id of cat, you get value using tag id for example,
            type: "GET",
            success: function () {
                swal("Done!", "It was succesfully deleted!", "success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                swal("Error deleting!", "Please try again", "error");
            }
        });
Swal.fire(
  'Deleted!',
  'Your file has been deleted.',
  'success'
)
}
	

Now once a user confirms the delete it will make a GET request to your defined route.

Just a side note, using a GET method for deleting things is a bad practice and can result in security issues (csrf), consider using DELETE method instead.

1 like

Please or to participate in this conversation.