mozew's avatar
Level 6

How to create pagination with ajax?

I have this view called categories/index.blade.php which gets included in index.blade.php:

@foreach($categories as $category)
    <tr>
        <td>{{ $category->name }}</td>
        <td>{{ $category->getParent->name }}</td>
        <td>
            <form action="{{ route('categories.destroy', ['id' => $category->id]) }}" method="post">
                @method('delete')
                @csrf()
                <div class="btn-group btn-group-sm">
                    <a href="{{ route('categories.edit' , ['id' => $category->id]) }}"  class="btn btn-primary">edit</a>
                    <button type="submit" class="btn btn-danger">delete</button>
                </div>
            </form>
        </td>
    </tr>
@endforeach
.
.   
.

{!! $categories->links() !!}

CategoryController.php

public function index(Request $request)
{
    if ($request->ajax()) {
        $categories = Category::latest()->paginate(5);
        return view('Admin.categories.index', compact('categories'));
    }
}

web.php

Route::resource('categories', 'CategoryController');

ajax

<script>
    $(document).ready(function () {
        $(document).onclick('.pagination a', function (event) {
            event.preventDefault();
            var page = $(this).attr('href').split('page=')[1];
            fetch_data(page);
        });
        function fetch_data(page) {
            $.ajax({
                url: 'fa/admin/categories?page='+page,
                success: function (data) {
                    $('.table-responsive').html(data);
                }
            })
        }
    });
</script>
0 likes
5 replies
siangboon's avatar

"answer my question" again and again...

Don't answer his question :laughing:

Snapey's avatar

answer what question?

¯\_(ツ)_/¯

mozew's avatar
Level 6

How tot create paagination with ajax in laravel?

Sinnbeck's avatar

What doesn't work? Are you getting an error? Or too much data? Or none at all?

What do you get if you console.log(data) in the success callback?

Please or to participate in this conversation.