Ad

Laravel Can't Confirm Delete With SweetAlert

- 1 answer

I have this problem with Sweetalert - I have the following code but the confirm modal is useless, as the request pass it and user don't even have time to decide. I have to figure it out to stop request executing and waits for user decision (Ok/Cancel).

Here's the code:

<a target="_blank" rel="nofollow noreferrer" href="{{route('notes.destroy', $note->id)}}" 
data-id="{{$note->id}}" onclick="confirmDelete('{{$note->id}}')" type="submit">
<span class="badge badge-danger">Delete</span></a>

and here's the jQuery (which I think it's the problem):

<script>
function confirmDelete(item_id) {
    swal({ 
        title: "Are you sure?",
        text: "Once deleted, you will not be able to recover it!",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    })
    .then((willDelete) => {
        if (willDelete) {
            $('#' + item_id).submit();
        } else {
            swal("Cancelled Successfully");
        }
    });
}
</script>
Ad

Answer

In blade file:

<link rel="stylesheet" target="_blank" rel="nofollow noreferrer" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>

<form id="delete_from_{{$note->id}}" method="POST" action="{{ route('post.destroy', $note->id) }}">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}

    <div class="form-group">
        <a target="_blank" rel="nofollow noreferrer" href="javascript:void(0);" data-id="{{$note->id}}" class="_delete_data">
            <span class="badge badge-danger">Delete</span>
        </a>                    
    </div>
</form>

js code:

<script>
    $(document).ready(function(){
        $('._delete_data').click(function(e){
            var data_id = $(this).attr('data-id');
            Swal.fire({
                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((result) => {

                if (result.value) {
                    $(document).find('#delete_from_'+data_id).submit();
                }
            })
        });
    });            
</script>
Ad
source: stackoverflow.com
Ad