php 动态添加/删除datatable列和数据 AJAX . [工程页面加载,但我通过ajax更改列表,它有错误]

xuo3flqw  于 2023-03-28  发布在  PHP
关注(0)|答案(1)|浏览(97)

我使用一个自定义列表来确定什么是数据的需要 AJAX 显示在datatable.[我添加btn在同一页面上点击后,在模态我显示字段列表中的复选框,保存它通过ajax和重新加载datatable js fn.]所以,如果用户在自定义列表中进行更改. datatable需要重新填充更多/更少的字段取决于自定义列表.
我目前的代码,我设法修改它的动态列表,但它的工作时,我重新加载页面。更新保存列表和 AJAX 函数调用。我面临的问题,如:添加新字段时:未捕获的类型错误:当我删除字段时,无法读取未定义的属性(阅读“样式”):未捕获的类型错误:无法读取未定义的属性(阅读“mData”)
我试图清空表,当我记录数据,它的显示目前,但仍然得到错误。我不知道为什么头和tbody数据不重新加载当前 AJAX 。请告知。我的刀片:

<table class="dt-responsive table datatable border-top" id="employee_table">
                <thead>
                    <tr>
                    <!-- @foreach($custom_field_list as $custom_field) 
                    <th scope="col">$custom_field->field_name</th>
                    @endforeach
                    <th scope="col">Actions</th> -->
                    </tr>
                </thead>
                <tbody>
                </tbody>

            </table>

my js for saving和tigger datatable fn:

$(".SubmitEmpFieldListForm").click(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.
        client_id = $('#employee_dropdown_clients').val();
        var formData = new FormData(document.getElementById("createEmpFieldListForm"));
        formData.append('client_id', client_id);
        $.ajax({
            url: "/hrm/employees/custom_fields_list",
            type: "POST",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            //data: name,
            success: function (result) {
                if (result.success.length > 0) {
                    $("#CreateEmpFieldListModal").modal("hide");
                    fetchEmployeeList("update");
                    swal("Done!", "Added succesfully!", "success");
                }
            },
            error: function (response) {
                console.log(response);
            },
        });
    });

我的js fn用于加载datatable。(当我重新加载页面时工作)

function fetchEmployeeList(type) {
    if (document.getElementById("employee_table")) {
        var useroptions = {
            processing: true,
            serverSide: true,
            lengthMenu: [
                [10, 25, 50, 100],
                [10, 25, 50, 100],
            ],
            iDisplayLength: 25,
            order: [1, "desc"],
            destroy: true,
            stateSave: true,
            ajax: {
                url: "/hrm/employees/getemployees",
                dataType: "json",
                type: "GET",
                data: function (data) {
                    console.log("getemployees");
                    var client_id = $('#employee_dropdown_clients').val();
                    data._token = "{{csrf_token()}}";
                    data.client_id = client_id;
                    
                },
            },
            columns: [],
        };

        
        // Fetch column names from the database
        $.ajax({
            url: '/hrm/employees/getcolumndata',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                $("#employee_table thead tr").empty();
                $("#employee_table tbody").empty();
                $.each(response, function(key, value) {
                    console.log("f::"+value.field_name);
                    var column = {
                        data: value.field_name,
                        title: value.field_name,
                    };
                    // Check if the column is an action column
                    if (value.field_name === 'Actions') {
                        column.bSortable = false;
                    }
                    useroptions.columns.push(column);
                });
                
                // Create the datatable
                if (type == "initial") {
                    useroptions.stateSave = false;
                    var employeeTable = $("#employee_table").DataTable(useroptions);
                } else {
                    var employeeTable = $("#employee_table").DataTable(useroptions);
                }
                
                // Bind the search event to the search input
                $("#employee_table_filter input").unbind();
                $("#employee_table_filter input").bind("keyup", function (e) {
                    if (e.keyCode == 13) {
                        employeeTable.search(this.value).draw();
                    }
                });
                
                // Add a responsive class to the datatable container
                $("#employee_table").parent().addClass("table-responsive");
            }
        });
    }
}

我的控制器:

public function getemployees(Request $request)
    {
        $customFields = '';
        $customFields = DB::table('employees_custom_field_list')
        ->select('table_name', 'field_name')
        ->get()
        ->toArray();
        $fieldName = '';
        $columns = array();
        foreach($customFields as $key => $field) {
            $table = $field->table_name;
            $fieldNameUpdate[] = $field->field_name;
            $fieldName = $field->field_name;
            $columns[$key] = $table.'.'.$fieldName;
        }
        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');
        $checkjoin = EmployeeCompanyDetail::where('client_id',$request->input('client_id'))->first();
        if($checkjoin != null || !empty($request->input('client_id'))){
            $dbdata = EmployeeBasicDetail::select('employees_basic_details.id');
            $dbdata = $dbdata->leftJoin('employees_company_details', 'employees_basic_details.id', '=', 'employees_company_details.employee_id');
            foreach($customFields as $field) {
                $table = $field->table_name;
                $fieldName = $field->field_name;
                $dbdata = $dbdata->addSelect($table.'.'.$fieldName);
            }
        }else{
            $dbdata = EmployeeBasicDetail::select('employees_basic_details.id');
            foreach($customFields as $field) {
                $table = $field->table_name;
                $fieldName = $field->field_name;
                $dbdata = $dbdata->leftJoin($table, 'employees_basic_details.id', '=', $table.'.employee_id')
                            ->addSelect($table.'.'.$fieldName);
            }
        }

        $totalData = $dbdata->count();
        $totalFiltered = $totalData;
        
        $dbdata = $dbdata->offset((int) $start);
        $dbdata = $dbdata->limit($limit);
        $dbdata = $dbdata->orderBy($order, $dir);
        $employeeData = $dbdata->get()->toArray(); 
        
        if (!empty($employeeData)) {
            $auth_user = Auth::user();
            $auth_role = $auth_user->currentRole(); 
            $data = array();
            foreach ($employeeData as $employee) {
                $encEmployee_id = \Illuminate\Support\Facades\Crypt::encrypt($employee['id']);
                $nestedData = [];
                foreach ($customFields as $key => $field) {
                    if (array_key_exists($field->field_name, $employee)) {
                        $nestedData[$field->field_name] = '<a href="/hrm/employees/'.$encEmployee_id.'/view" >'.$employee[$field->field_name].'</a>';
                    }
                }

                
                $data[] = $nestedData;
            }
        }
        //dd($data);
        $json_data = array(
            "draw" => intval($request->input('draw')),    
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data,
            "header" => $fieldNameUpdate,
        );
        echo json_encode($json_data);
        

    }

    public function getcolumndata()
    {
        $auth_user = Auth::user();
        $client_id=$auth_user->client_id;
        $custom_field_list = EmployeeCustomFieldList::where(['client_id'=>$client_id,'user_id'=>$auth_user->id])->get();
        return $custom_field_list;
    }
rggaifut

rggaifut1#

我发现这个问题。问题是datatable不刷新当我下一个电话,所以我发现在互联网上的以下代码,它的解决问题。

if ( $.fn.DataTable.isDataTable( '#employee_table' ) ) {
        $('#employee_table').DataTable().destroy();
        $('#employee_table').empty();
     };

相关问题