首页 > 解决方案 > Repopulating table data in Laravel Pagination using JQUERY and AJAX

问题描述

How to repopulate the table data when clicking the page number 2 or any other pages? I am struggling on how to do that with JSON data coming from the ajax response. Please Help, Thank you!. Here is my code

Controller

    function associate(Request $request)
{
    $associate = User::join('associate', 'associate.associate_id', '=', 'users.id')
    ->orderBy('last_name', 'ASC')
    ->paginate(5);

    if ($request->ajax()) {
        return response()->json($associate);
    }

    return view('dashboards.admin.manageassociate', [
       'associate' => $associate
    ]);
}

Blade View

 $(document).ready(function() {

        fetchassociate();

        function fetchassociate() {
            $.ajax({
                type: "GET",
                url: "{{route('admin.associate')}}",
                dataType: "json",
                success: function(response) {
                     console.log(response.data);
                    $('tbody').html("");
                    $('#tablefoot').html("");
                    $.each(response.data, function(key, associates) {
                        $('tbody').append('<tr>\
                            <td>' + associates.associate_id + '</td>\
                            <td>' + associates.last_name + ', ' + associates.first_name + ' ' + associates.middle_name + '</td>\
                            <td>' + associates.username + '</td>\
                            <td>' + associates.email + '</td>\
                            <td>' + associates.phone + '</td>\
                            <td>' + associates.gender + '</td>\
                            <td><button type = "button" value = "' + associates.associate_id + '" class = "edit_associate btn btn-primary btn-sm">Edit</button>\
                            <button type = "button" value = "' + associates.associate_id + '" class = "delete_associate btn btn-danger btn-sm">Delete</button></td>\
                            </tr>');
                    });
                        $.each(response.links, function(key, link) {
                        $('#tablefoot').append( '<li class="page-item"><a class="page-link" href="'+link.url+'">'+link.label+'</a></li>');
                    });
                }

            });
        }

}

Route

Route::get('manage_associates', [ManageController::class, 'associate'])->name('admin.associate');

标签: javascriptjqueryajaxlaravellaravel-8

解决方案


I already solved this problem by changing the url route and adding an on-click function on the pagination.


推荐阅读