过滤后如何显示数据表元素? Laravel + Ajax

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

我的数据显示在带有数据表的表格中,但每次过滤时,我都没有得到表中可用的数据。但奇怪的是,在控制台中,它通过了过滤器。

$('#categoryFilter').select2();

function filterByCategory(category) {
    $.ajax({
        type: 'post',
        data: {
            _token: csrf_token,
        },
        url: '/product/filterByCategory/' + category,
        success: function (data) {
            console.log( data);
            $('#tableProducts').DataTable().clear().rows.add(data).draw();
        },
        error: function (resp) {
            console.log(resp);
        }
    });
}

过滤后的结果:

the result after filtering

ajax laravel datatables
1个回答
0
投票

我曾经使用 Yajra Datatable 中的 select2 库创建了一个过滤器功能。这是代码片段;也许这可以给你一个解决问题的想法。

查看

@extends('layouts.user')
@section('title', 'Reservations')
@section('content')
<div id="kt_app_toolbar" class="app-toolbar py-3 py-lg-6">
    <div id="kt_app_toolbar_container" class="app-container container d-flex flex-stack">
        <div class="page-title d-flex flex-column justify-content-center flex-wrap me-3">
            <h1 class="page-heading d-flex text-dark fw-bold fs-3 flex-column justify-content-center my-0">Reservations</h1>
            <ul class="breadcrumb breadcrumb-separatorless fw-semibold fs-7 my-0 pt-1">
                <li class="breadcrumb-item text-muted">
                    <a href="{{ route('user.dashboard') }}">Home</a>
                </li>
                <li class="breadcrumb-item">
                    <span class="bullet bg-gray-400 w-5px h-2px"></span>
                </li>
                <li class="breadcrumb-item text-muted">Reservations</li>
            </ul>
        </div>
    </div>
</div>
<div id="kt_app_content" class="app-content flex-column-fluid">
    <div id="kt_app_content_container" class="app-container container">
        <div class="card border">
            <div class="card-header border-0 pt-6">
                <div class="card-title align-items-start flex-column">
                    <span class="svg-icon svg-icon-1 position-absolute ms-6">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                            <rect opacity="0.5" x="17.0365" y="15.1223" width="8.15546" height="2" rx="1" transform="rotate(45 17.0365 15.1223)" fill="currentColor" />
                            <path
                                d="M11 19C6.55556 19 3 15.4444 3 11C3 6.55556 6.55556 3 11 3C15.4444 3 19 6.55556 19 11C19 15.4444 15.4444 19 11 19ZM11 5C7.53333 5 5 7.53333 5 11C5 14.4667 7.53333 17 11 17C14.4667 17 17 14.4667 17 11C17 7.53333 14.4667 5 11 5Z"
                                fill="currentColor" />
                        </svg>
                    </span>
                    <input type="search" name="search" class="form-control form-control-solid ps-15 w-lg-250px w-150px" id="search" placeholder="Search.." />
                </div>
                <div class="card-toolbar">
                    <div class="d-flex justify-content-end" data-kt-user-table-toolbar="base">
                        <button type="button" class="btn btn-sm btn-light-primary me-3" data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end">
                        <i class="ki-duotone ki-filter fs-2">
                            <span class="path1"></span>
                            <span class="path2"></span>
                        </i>Filter
                        </button>
                        <div class="menu menu-sub menu-sub-dropdown w-300px w-md-325px" data-kt-menu="true">
                            <div class="px-7 py-5">
                                <div class="fs-5 text-dark fw-bold">Filter Options</div>
                            </div>
                            <div class="separator border-gray-200"></div>
                            <div class="px-7 py-5">
                                <div class="mb-10">
                                    <label class="form-label fs-6 fw-semibold">Status:</label>
                                    <select name="status" class="form-select form-select-solid fw-bold" data-kt-select2="true" data-placeholder="Select option" data-allow-clear="true" id="filterByStatus" data-hide-search="true">
                                        <option></option>
                                        <option value="confirmed">Confirmed</option>
                                        <option value="pending">Pending</option>
                                        <option value="cancelled">Cancelled</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body py-4">
                <table class="table align-middle table-row-dashed fs-6 gy-5" id="dataTable">
                    <thead>
                        <tr class="text-start text-dark fw-bold fs-7 text-uppercase gs-0">
                            <th class="min-w-125px">No</th>
                            <th class="min-w-75px">Booking code</th>
                            <th class="min-w-125px">Property</th>
                            <th class="min-w-75px">Check-in</th>
                            <th class="min-w-75px">Check-out</th>
                            <th class="min-w-75px">No. of guests</th>
                            <th class="min-w-75px">Total payment</th>
                            <th class="min-w-75px">Status</th>
                            <th class="text-end min-w-75px">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="text-dark fw-semibold"></tbody>
                </table>
            </div>
        </div>
    </div>
</div>
@endsection
@push('scripts')
<script>
    $(document).ready(function() {
        var datatable = $('#dataTable').DataTable({
            processing: true,
            serverSide: true,
            ordering: true,
            pageLength: 25,
            stateSave: false,
            ajax: {
                url: '{!! url()->current() !!}',
                data: function (d) {
                    d.status = $('#filterByStatus').val();
                }
            },
            columns: [
                {   
                    name: 'DT_RowIndex', 
                    data: 'DT_RowIndex', 
                    orderable: false, 
                    searchable: false 
                },
                {   data: 'booking_code',
                    name: 'booking_code',
                    orderable: true,
                    searchable: true, 
                    width: '10%'
                },
                {   data: 'property',
                    name: 'property',
                    orderable: true,
                    searchable: true, 
                    width: '20%'
                },
                {   data: 'check_in',
                    name: 'check_in',
                    orderable: true,
                    searchable: true, 
                    width: '15%'
                },
                {   data: 'check_out',
                    name: 'check_out',
                    orderable: true,
                    searchable: true, 
                    width: '15%'
                },            
                {   
                    data: 'number_of_guests',
                    name: 'number_of_guests',
                    orderable: true,
                    searchable: true, 
                    width: '15%'
                },
                {   data: 'total_amount',
                    name: 'total_amount',
                    orderable: true,
                    searchable: true, 
                    width: '15%'
                },
                {
                    data: 'status',
                    name: 'status',
                    orderable: true,
                    searchable: true, 
                    width: '10%'
                },
                {   data: 'action',
                    name: 'action',
                    orderable: true,
                    searchable: true, 
                    width: '10%'
                },
            ],
            columnDefs: [
                {
                    "targets": [ 0 ],
                    "visible": false,
                    "searchable": false
                }                     
            ],
            order: [[ 0, "desc" ]]
        })
    
        $('#search').on( 'keyup', function () {
            datatable.search( this.value ).draw();
        } );

        $('#filterByStatus').on('change', function(e) {
            e.preventDefault();
            datatable.draw();
        });

    });
</script>
@endpush

控制器

public function index(Request $request)
{
    try {
        if ($request->ajax()) {
            $query = Booking::with(['user','guests','payments','property'])->confirmed()
                    ->whereHas('property', function ($query) {
                        $query->where('user_id', auth()->user()->id);
                    })->latest();

            return DataTables::of($query)
                ->addIndexColumn()
                ->editColumn('booking_code', function ($item) {
                    return $item->booking_code ?? '-';
                })
                ->addColumn('property', function ($item) {
                    return '
                    <div class="d-flex flex-column">
                        <a href="'.route('front.property-detail',$item->property->slug).'" target="_blank" class="text-gray-800 text-hover-primary mb-1">'.$item->property->title.'</a>
                    </div>';
                })
                ->editColumn('check_in', function ($item) {
                    return Carbon::parse($item->check_in)->format('M d, Y');
                })
                ->editColumn('check_out', function ($item) {
                    return Carbon::parse($item->check_out)->format('M d, Y');
                })
                ->editColumn('number_of_guests', function ($item) {
                    return $item->number_of_guests > 1 ? $item->number_of_guests.' guests' : $item->number_of_guests.' guest';
                })
                ->editColumn('total_amount', function ($item) {
                    return '$'.number_format($item->total_amount, 0, ',', '.');
                })
                ->editColumn('status', function ($item) {
                    if ($item->status == 'confirmed') {
                        return '<span class="badge badge-light-success">Confirmed</span>';
                    } elseif ($item->status == 'cancelled') {
                        return '<span class="badge badge-light-danger">Cancelled</span>';
                    } elseif ($item->status == 'rejected') {
                        return '<span class="badge badge-light-danger">Rejected</span>';
                    } else {
                        return '<span class="badge badge-light-warning">Pending</span>';
                    }
                })
                ->addColumn('action', function ($item) {
                    $button =  '<div class="float-end">
                                    <a href="'.route('user.reservations.show',$item->id).'" class="btn btn-icon btn-icon-dark btn-text-dark btn-bg-light btn-active-color-info border-2-brand-primary rounded-circle btn-30px me-1" data-id="' . $item->id . '">
                                    <i class="ki-duotone ki-eye fs-3"><span class="path1"></span><span class="path2"></span><span class="path3"></span></i>
                                    </a>
                                    <a role="button" class="btn btn-icon btn-icon-dark btn-text-dark btn-bg-light btn-active-color-danger border-2-brand-primary rounded-circle btn-30px delete-confirm" id="deleteConfirm" data-id="' . $item->id . '">
                                        <i class="ki-duotone ki-trash fs-3"><span class="path1"></span><span class="path2"></span><span class="path3"></span><span class="path4"></span><span class="path5"></span></i>
                                    </a>
                                </div>';

                    return $button;
                })
                ->filter(function ($query) use ($request) {
                    if ($request->has('status') && !empty($request->status)) {
                        $query->where('status', $request->status);
                    }
                })
                ->rawColumns(['property','status', 'action'])
                ->make(true);
        }

        return view('host.reservations.index');
    } catch (\Throwable $th) {
        return back()->with('toast_error', $th->getMessage());
    } 
}
© www.soinside.com 2019 - 2024. All rights reserved.