php AJAX 不会删除Laravel中的行

idfiyjo8  于 2023-01-12  发布在  PHP
关注(0)|答案(1)|浏览(131)

我在Laravel中使用DataTables,我的目标是从数据库中删除一行,然后重新加载数据列表。但由于某种原因,它不起作用。我收到-Data Not Deleted错误,而且setTimeOut函数似乎不起作用,因为消息没有消失。我是 AJAX 的新手,所以很难找到错误的原因。按钮:

$button = '   <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"> <i class="fas fa-fw  fa-trash"></i> Delete</button>';

单击删除按钮时显示的HTML表单:

<div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
        <div class="modal-dialog">
        <div class="modal-content">
        <form method="post" id="sample_form" class="form-horizontal">
            <div class="modal-header">
                <h5 class="modal-title" id="ModalLabel">Confirmation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
            </div>
        </form>
        </div>
        </div>
    </div>

脚本:

var employee_id;

        $(document).on('click', '.delete', function(){
            employee_id = $(this).attr('id');
            $('#confirmModal').modal('show');
        });

        $('#ok_button').click(function(){
            $.ajax({
                url:"/admin/employees/destroy/"+employee_id,
                beforeSend:function(){
                    $('#ok_button').text('Deleting...');
                },
                success:function(data)
                {
                    setTimeout(function(){
                    $('#confirmModal').modal('hide');
                    $('#employee_table').DataTable().ajax.reload();
                    alert('Data Deleted');
                    }, 2000);
            },
            error: function(xhr, status, error) {
                setTimeout(function(){
                    $('#confirmModal').modal('hide');
                    $('#employee_table').DataTable().ajax.reload();
                    alert('Data Not Deleted');
                    }, 2000);
            },
            })
        });
    });

途径:

Route::get('/admin/employees/destroy/{id}', [EmployeeController::class, 'destroy']);

控制器功能:

public function destroy($id)
    {
        $data = Employee::findOrFail($id);
        $data->delete();
    }
sbdsn5lh

sbdsn5lh1#

在“form”中,你有POST方法,但是在Route中,你有Get方法。
我会尝试把以下标签:

<form method="post" id="sample_form" class="form-horizontal">
@csrf
@method('DELETE')
..

或者在 AJAX call中添加以下内容,而不是@csrf和@method:

type: 'DELETE',

然后将路线从获取修改为删除:

Route::Delete('/admin/employees/destroy/{id}', [EmployeeController::class, 'destroy']);

相关问题