最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Delete method with Sweet Alert in Laravel - Stack Overflow

programmeradmin5浏览0评论

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.

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.

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.

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.

Share Improve this question edited Nov 13, 2016 at 22:37 Edward Palen asked Nov 13, 2016 at 22:29 Edward PalenEdward Palen 5654 gold badges15 silver badges29 bronze badges 2
  • Have a look at this. stackoverflow.com/questions/31136889/… – usrNotFound Commented Nov 14, 2016 at 1:49
  • Hello @CannotFindSymbol and thank you very much, but with this method eliminates the user and does not generate the notification. – Edward Palen Commented Nov 14, 2016 at 2:57
Add a comment  | 

6 Answers 6

Reset to default 6

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');
}

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');

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();
                }
            })
        });

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>

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'
                        })
                    }
                })
            }
        });
}
<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>
发布评论

评论列表(0)

  1. 暂无评论