4

I'm testing a method using Sweet Alert, to improve the messages issued by the Javascript alert method with the laravel framework.

1 - I downloaded the files sweetalert.css and sweetalert.min.js.

2 - So I connect the files from app.blade.php

<!-- Sweet Alert -->
<link href="{{ asset('/dist/css/sweetalert.css') }}" rel="stylesheet">
<!-- Sweet Alert -->
<script src="{{ asset('/dist/js/sweetalert.min.js') }}"></script>

3 - I created the delete button using the onclick event of Javascript and the following Sweet Alert function:

{!! Form::open(['method' => 'DELETE','route' => ['users.destroy', $user->id],'style'=>'display:inline']) !!}
<button onclick="
 swal({
  title: 'Esta seguro de realizar esta Acción?',
  text: 'Si procede este usuario será eliminado!',
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#DD6B55',
  confirmButtonText: 'Eliminar!',
  cancelButtonText: 'Cancelar',
  closeOnConfirm: false,
  closeOnCancel: false
},
function(){
  swal('Usuario eliminado!', 'Este usuario fue eliminado de nuestros registros.', 'success');
});"
  class="btn btn-danger" data-toggle="tooltip" data-placement="top" title="Eliminar usuario"> <i class="material-icons">delete</i> 
</button>
{!! Form::close() !!}

4 - This is my method for deleting users from UserController:

public function destroy($id)
{
    User::find($id)->delete();
    return redirect()->route('users.index')
                    ->with('success','User deleted successfully');
}

5 - The problem occurs when deleting a user, displays the alert message.

Message generated by Sweet Alert

But automatically closes and deletes the user without allowing to take the confirmation actions, whether or not to delete the user, method defined in Sweet Alert.

Someone who can give a help to correct this problem or recommend a better method, since I am using Laravel as Framework.

Edward Palen
  • 565
  • 4
  • 14
  • 29
  • Have a look at this. http://stackoverflow.com/questions/31136889/how-to-use-confirm-using-sweet-alert – usrNotFound Nov 14 '16 at 01:49
  • Hello @CannotFindSymbol and thank you very much, but with this method eliminates the user and does not generate the notification. – Edward Palen Nov 14 '16 at 02:57

6 Answers6

5

You are Performing action on button click irrespective of whether you confirm or cancelled the deletion.

<a href="" class="button" data-id="{{$user->id}}">Delete</a>

Jquery and Ajax:

$(document).on('click', '.button', function (e) {
    e.preventDefault();
    var id = $(this).data('id');
    swal({
            title: "Are you sure!",
            type: "error",
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes!",
            showCancelButton: true,
        },
        function() {
            $.ajax({
                type: "POST",
                url: "{{url('/destroy')}}",
                data: {id:id},
                success: function (data) {
                              //
                    }         
            });
    });
});

And:

public function destroy(Request $request)
{
    User::find($request->id)->delete();
    return redirect()->route('users.index')
                    ->with('success','User deleted successfully');
}
Sanzeeb Aryal
  • 4,358
  • 3
  • 20
  • 43
  • Thank you very much for your answer, I was trying to apply your method but I can not get it to work. It only generates the window to confirm whether or not to proceed with the action, but the record is not deleted. The error is as follows: – Edward Palen Nov 14 '16 at 21:38
  • POST http://localhost/zizaco_entrust/public/destroy 500 (Internal Server Error)send @ jquery.min.js:4ajax @ jquery.min.js:4(anonymous function) @ users?page=3:429l @ sweetalert.min.js:1s @ sweetalert.min.js:1g @ sweetalert.min.js:1 – Edward Palen Nov 14 '16 at 21:40
  • the error is with the server. make sure you have the route: `Route::post('/destroy','UserController@destroy');` – Sanzeeb Aryal Nov 15 '16 at 02:42
  • 1
    Thank you very much. In the end I had to add a location.reload (); To refresh the page after the event. Many thanks. – Edward Palen Nov 15 '16 at 19:04
  • Why I can't get the value data-id="{{$user->id}}" by using var id = $(this).data('id'); – matthew chick Aug 09 '20 at 11:34
5

in the view :

<button onclick="deleteItem(this)" data-id="{{ $user->id }}">Delete</button>

in the Jquery and Ajax :

<script type="application/javascript">

        function deleteItem(e){

            let id = e.getAttribute('data-id');

            const swalWithBootstrapButtons = Swal.mixin({
                customClass: {
                    confirmButton: 'btn btn-success',
                    cancelButton: 'btn btn-danger'
                },
                buttonsStyling: false
            });

            swalWithBootstrapButtons.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, cancel!',
                reverseButtons: true
            }).then((result) => {
                if (result.value) {
                    if (result.isConfirmed){

                        $.ajax({
                            type:'DELETE',
                            url:'{{url("/user/delete")}}/' +id,
                            data:{
                                "_token": "{{ csrf_token() }}",
                            },
                            success:function(data) {
                                if (data.success){
                                    swalWithBootstrapButtons.fire(
                                        'Deleted!',
                                        'Your file has been deleted.',
                                        "success"
                                    );
                                    $("#"+id+"").remove(); // you can add name div to remove
                                }

                            }
                        });

                    }

                } else if (
                    result.dismiss === Swal.DismissReason.cancel
                ) {
                    swalWithBootstrapButtons.fire(
                        'Cancelled',
                        'Your imaginary file is safe :)',
                        'error'
                    );
                }
            });

        }

    </script>

in the Controller:

public function destroy(User $user, Request $request, $id)
    {
        if ($request->ajax()){

            $user = User::findOrFail($id);

            if ($user){

                $user->delete();

                return response()->json(array('success' => true));
            }

        }
    }

in the Route

Route::delete('/user/delete/{id}','UserController@destroy');
Abdulmajeed
  • 552
  • 7
  • 8
4

I think my code is closer to the Laravel framework, it has CSRF and it uses the Delete method; also it is more easy to integrate.

Laravel 8 and SweetAlert 2

UserController:

public function destroy(User $user)
{
    $user->delete();
    toast('Your file has been deleted !', 'success');
    return redirect(route('user.index'));
}

Delete html form: bootstrap used for css classes

<form id="delete-user-form" action="{{route('user.destroy',$user)}}" method="POST">
    @csrf
    @method('DELETE')
    <button onclick="return false" id="delete-user" class="btn btn-danger">Delete</button>
</form>

jQuery

 $('#delete-user').on('click', function (e) {
            e.preventDefault();
            let id = $(this).data('id');
            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) {
                    $('#delete-post-form').submit();
                }
            })
        });
Community
  • 1
  • 1
Arash Younesi
  • 1,671
  • 1
  • 14
  • 23
1

I have implemented this code into my laravel project and my route is resource route for destroy. This code is worked for me. As in above comment location.reload() help me and I put it into code...plz try and let me know...it worked for you or not...

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
//.deletebutton is the class name in button
<script>
    $('.deletebutton').on('click', function () {
        // return confirm('Are you sure want to delete?');
        event.preventDefault();//this will hold the url
        swal({
            title: "Are you sure?",
            text: "Once clicked, this will be softdeleted!",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        })
        .then((willDelete) => {
            if (willDelete) {
                swal("Done! category has been softdeleted!", {
                    icon: "success",
                    button: false,
                });
            location.reload(true);//this will release the event
            } else {
                swal("Your imaginary file is safe!");
            }
        });
    });
</script>
Neeraj Tangariya
  • 1,159
  • 1
  • 17
  • 29
0

I have implemented this code in my laravel project and delete data by using route name with slug. This code is working for me. And i also delete row from table without reload() by using with id. So try this code let me know it's working for you or not.

 $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

function confirmDelete(slug) {
    swal({
            title: "Are you sure!",
            type: "error",
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes!",
            showCancelButton: true,
        })
        .then((willDelete) => {
            if (willDelete.value == true) {
                var url = '{{ route("instrument.delete", ":slug") }}';
                url = url.replace(':slug', slug);
                $.ajax({
                    url: url,
                    type: "POST",
                    data: {
                        '_method': 'DELETE'
                    },
                    success: function (data) {
                        if (data.status == 1) {
                            swal({
                                title: "Success!",
                                type: "success",
                                text: "Instrument has been deleted \n Click OK",
                                icon: "success",
                                confirmButtonClass: "btn btn-outline-info",
                            });
                            $('#tr' + data.slug).remove();
                        }

                    },
                    error: function (data) {
                        swal({
                            title: 'Opps...',
                            text: data.message,
                            type: 'error',
                            timer: '1500'
                        })
                    }
                })
            }
        });
}
Fahad Ahmad
  • 63
  • 1
  • 6
-1
<script>
  $('.delete').click(function() {
    var id= $(this).attr('data-id');
    swal({
        title: "Apakah Anda Yakin ?",
        icon: "info",
        buttons: true,
        dangerMode: true,
      })
      .then((willDelete) => {
        if (willDelete) {
          window.location = "/delete/" + ""
          swal("Deleted!", {
            icon: "success",
          });
        } else {
          swal({
            title: "Canceled`enter code here` !?",
            icon: "error",

          });
        }
      });
  });
</script>
joe
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 18 '23 at 12:00