Search code examples
jquerylaravel-5sweetalert2

Proper way to make a soft delete using sweetalert2


Hello guys I'm using sweetalert2, this is already function but there are some bugs that need to be fix.

bugs:

  1. When I click ok the location.reload() will be triggered without hitting "OK".

  2. When I click cancel the modal is still in popup mode.

This is my script.

$('body').on('click','.delete-category',function(){
            deleteCategory();
        });

        function deleteCategory(id){

           var id = $('body').find('#categoryTable tbody tr.selected .catId').val();
           console.log(id);

            swal({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then(function(isConfirm){
                if (isConfirm) {
                    $.ajax({
                        url: `/asset/category-delete/${id}`,
                        method: 'DELETE',
                        data: { _token: '{{ csrf_token()}}' },
                        success: function(data){
                            swal(
                                'Deleted!',
                                'Your file has been deleted.',
                                'success' 
                            );
                            location.reload();
                            },
                        error: function(err){
                            swal('Error!','Please report this issue.', 'error');
                        }
                    });
                } else {
                swal("Cancelled","", "error");
                }
            });
        }

Looking for enhancement.


Solution

  • About your bug #1: You have to place location.reload(); in a then() method if you want if to be executed after a swal interaction.

    success: function(data){
      swal(
        'Deleted!',
        'Your file has been deleted.',
        'success' 
      ).then(()=>{
        location.reload();
      });
    },
    

    About your bug #2: I can't figure out what «delete modal» you talk about...