Laravel 从 Ajax 调用中删除记录 - 按钮单击事件不起作用

问题描述 投票:0回答:1

我正在尝试从 laravel CRUD 中的 ajax 调用中删除一条记录。但点击事件似乎不起作用。因此删除功能不起作用。这是我的代码。

web.php

Route::delete('/categories/destroy/{id}', [CategoryController::class, 'destroy'])->name('categories.destroy');

CategoryController.php

public function index(Request $request){
        $categories = CategoryModel::select('id', 'name', 'type');

        if ($request->ajax()){
            return DataTables::of($categories)
                ->addColumn('action', function ($row){
                   return '<a href="javascript:void(0)" class="btn btn-info editButton" data-id="'.$row->id.'">Edit</a>
                            <a href="javascript:void(0)" class="btn btn-danger" id="delButton" data-id="'.$row->id.'">Delete</a>';
                })
                ->rawColumns(['action'])
                ->make(true);
        }
    }

public function destroy($id){
        $category = CategoryModel::find($id);
        if (! $category){
            abort(404);
        }
        $category->delete();
        return response()->json([
            'success'=>'Category Deleted Successfully'
        ], 201);
    }

create.blade.php

<body>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="modal-title"></h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="" id="cretateCategoryForm">
                <div class="modal-body">
                    <input type="hidden" name="category_id" id="category_id">
                    <div class="form-group mb-3">
                        <label for="" class="">Name</label>
                        <input type="text" name="name" id="name" class="form-control">
                        <span id="nameError" class="text-danger error-messages"></span>
                    </div>
                    <div class="form-group">
                        <label for="" class="">Category Name</label>
                        <select id="type" name="type" class="form-control mb-1">
                            <option disabled selected>Choose Option</option>
                            <option value="electronic">Electronics</option>
                        </select>
                        <span id="typeError" class="text-danger error-messages"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary"id="saveBtn"></button>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-6 offset-3" style="margin-top: 100px;">
        <a href="" class="btn btn-info mb-3" data-bs-toggle="modal" data-bs-target="#exampleModal" id="add_category">Add Category</a>

        <table class="table" id="category-table">
            <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">Name</th>
                <th scope="col">Type</th>
                <th scope="col">Action</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.min.js"></script>
<script>
    $(document).ready(function () {

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

        var table = $('#category-table').DataTable({
            processData: true,
            serverSide: true,

            ajax: "{{ route('categories.index') }}",
            columns: [
                { data: 'id' },
                { data: 'name' },
                { data: 'type' },
                { data: 'action', name: 'action', orderable: false, searchable:false },
            ]
        })

       $('#modal-title').html('Create Category');
       $('#saveBtn').html('Save Category');

       var form = $('#cretateCategoryForm')[0];
       $('#saveBtn').click(function () {

            $('.error-messages').html('');
            var formData = new FormData(form);

            $.ajax({
                url: '{{ route("categories.store") }}',
                method: 'POST',
                processData: false,
                contentType: false,
                data: formData,

                success: function (response) {
                    table.draw();
                    $('#name').val('');
                    $('#type').val('');
                    $('#category_id').val('');
                    if(response){
                        $('#exampleModal').modal('hide');
                        swal("Success!", response.success, "success");
                    }
                },
                error: function (error) {
                    if(error){
                        console.log(error.responseJSON.errors.name);
                        $('#nameError').html(error.responseJSON.errors.name);
                        $('#typeError').html(error.responseJSON.errors.type);
                    }
                }
            });
       });

            $('body').on('click', '#delButton', function (){
                var id  = $(this).data('id');

                $.ajax({
                    url: '{{ url("/categories/destroy", '') }}' + '/' + id,
                    method: 'DELETE',

                    success: function (response){
                        table.draw();
                        swal("Success!", response.success, "success");
                    },
                    error: function (error){
                        console.log(error)
                    }
                });
            });
            
        });
    });
</script>
</body>
</html>

我尽了一切努力。 stackoverflow 之前针对类似问题的解决方案都不起作用。请帮我。谢谢!

jquery json ajax laravel
1个回答
0
投票

id 属性的值必须是唯一的,才能访问和操作具有特定 id 的元素。所以,你可以通过类名来触发点击事件 -

$('body').on('click', '.btn-danger', function (){
    ....
})
© www.soinside.com 2019 - 2024. All rights reserved.