laravel_ninja's avatar

Laravel Ajax pagination not working

I'm trying to use Ajax pagination in Laravel using object partials but that's not working as I'm expecting . On first click it's loading data without page reload on second click it's loading data with page reload . I don't know why . May I get help from anyone . Here is my index blade code

<!DOCTYPE html>
<html lang="en" class="scroll-smooth">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"
        rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
        crossorigin="anonymous"></script>
    <!-- <script src="./index.js"></script> -->
    {{-- <link rel="stylesheet" href="/resources/css/app.css" /> --}}
    @vite('resources/css/app.css')
    <title>Admin Dashboard</title>
</head>

<body class="bg-bodyBg font-poppins">
    <nav
        class=" flex  justify-around justify-items-center bg-baseGray py-4 border-b-baseOrange border-b-2 h-16 md:flex-col md:items-center md:gap-y-2 sm:gap-y-2">
        <h1 class="uppercase text-baseWhite font-sans tracking-wide cursor-pointer font-bold md:hidden sm:capitalize ">
            Ninja <span class="text-baseOrange">Garage</span>
        </h1>
        <ul class="flex space-x-12 lg:flex sm:space-x-3">

            <li class="uppercase">
                <a title="Admin Dashboard" class="text-baseWhite hover:text-baseOrange"
                    href="{{ route('adminDashboard') }}">{{ $user->name }}</a>
            </li>
            <li class="uppercase">
                <a class="uppercase bg-baseOrange text-baseWhite    py-0.5 px-7 rounded-md font-medium"
                    href="{{ route('adminVendors') }}">Vendors</a>
            </li>
        </ul>
        <div>
            <a class=" bg-baseOrange text-baseWhite    py-0.5 px-7 rounded-md font-medium "
                href="{{ route('logout') }}">Logout</a>

            <a class=" bg-baseOrange text-baseWhite    py-0.5 px-7 rounded-md font-medium "
                href="{{ route('showSearch') }}">Go to
                Serach</a>
        </div>


    </nav>

    <main class="w-full " id="main-section">
        @include('tailwind.partials.admin_dashboard_card')
    </main>
    <footer class="fixed hidden bottom-0 bg-baseOrange w-full h-14">
        <p
            class="capitalize absolute mx-auto w-full text-baseWhite cursor-pointer mt-5 font-bold text-center  sm:font-small sm:text-sm">
            All right Reserved Ninja Garage,INC 2022
        </p>
    </footer>
    <script>
        $(document).ready(function() {

            $('.pagination').click(function(e) {
                e.preventDefault();
                let pageNumber = $(this).attr('href').split('page=');
                let page = parseInt(pageNumber[1]);
                console.log(page);
                console.log("Clicked ");
                fetchData(page);
            });
            $('.pre-page').click(function(e) {
                e.preventDefault();
                console.log('Previous clicked');
            });
            $('.next-page').click(function(e) {
                e.preventDefault();
                console.log('Next clicked');
            });


            function fetchData(page) {
                console.log("Here in fetchData");
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $.ajax({
                    method: 'POST',
                    url: "{{ route('adminDashboardAdsPagination') }}",
                    data: {
                        page: page
                    },
                    success: function(data) {
                        $('#main-section').html(data);
                        // console.log(data);
                    },
                    error: function(data) {
                        console.log(data.status);
                    }
                });

            }
        });
    </script>
</body>

</html>
Here is partial object
<div class="cards flex justify-center flex-col gap-y-9 my-5">
    @foreach ($ads as $ad)
        <div
            class="card   w-9/12 mx-auto bg-lightGray flex justify-around  items-center  rounded
    md:w-11/12  sm:flex-col
    ">
            <img class="h-52 rounded w-44 overflow-hidden
    sm:h-44 sm:w-44 sm:rounded-full
    "
                src="/uploads/images/{{ $ad->images[0] }}" alt="Car Image" />
            <div class="information flex flex-col  space-y-4  justify-items-center
    md:space-y-2 sm:space-y-0
    ">
                <h1 class=" uppercase font-bold text-baseWhite md:font-medium md:capitalize">{{ $ad->car_make }}
                </h1>
                <h2 class="text-baseWhite md:font-medium">{{ $ad->user->city }}</h2>
                <div class="car-information">
                    <h2 class="inline text-baseWhite      md:block md:mx-0 md:font-medium">{{ $ad->car_model }}
                    </h2>
                    <h2 class="inline text-baseWhite mx-3 md:block md:mx-0 md:font-medium ">{{ $ad->car_color }}
                    </h2>
                    <h2 class="inline text-baseWhite mx-3 md:block md:mx-0 md:font-medium ">
                        {{ $ad->car_millage }}Km</h2>
                </div>
                <h2 class="text-baseWhite">
                    <span class="font-medium text-baseOrange">Updated:</span>
                    {{ $ad->updated_at->diffForHumans() }}
                </h2>
            </div>
            <div class="details flex flex-col space-y-20 sm:space-y-5">
                @if ($ad->isFeatured)
                    <h1 class="bg-baseOrange  py-1 px-5 text-baseWhite rounded">Featured </h1>
                @endif
                <a title="Go to Details " class="py-1 px-5   font-medium text-baseOrange bg-baseWhite rounded"
                    href="{{ route('adminShowAd', $ad->id) }}">Details</a>
            </div>
        </div>
    @endforeach
</div>
</div>
{{ $ads->links() }}
Below is my tailwind template
@if ($paginator->hasPages())
    <div id="paginator" class="flex items-center justify-center space-x-1   mt-3">
        {{-- Previous Page Link --}}
        @if ($paginator->onFirstPage())
            <span
                class="rounded-l rounded-sm border border-solid border-darkGray px-3 py-2  bg-baseGray cursor-not-allowed no-underline">&laquo;</span>
        @else
            <a class="pagination rounded-l rounded-sm border border-solid border-darkGray px-3 py-2
            bg-baseOrange
             text-brand-dark hover:bg-brand-light no-underline"
                href="{{ $paginator->previousPageUrl() }}" rel="prev">
                &laquo;
            </a>
        @endif

        {{-- Pagination Elements --}}
        @foreach ($elements as $element)
            {{-- "Three Dots" Separator --}}
            @if (is_string($element))
                <span
                    class=" border-t border-b border-l border-brand-light px-3 py-2    bg-baseOrange cursor-not-allowed no-underline">{{ $element }}</span>
            @endif

            {{-- Array Of Links --}}
            @if (is_array($element))
                @foreach ($element as $page => $url)
                    @if ($page == $paginator->currentPage())
                        <span
                            class="pagination border border-solid border-darkGray  px-3 py-2
                            bg-baseGray  rounded-md   no-underline">{{ $page }}</span>
                    @else
                        <a class="pagination border-t border border-solid border-darkGray px-3 py-2 bg-baseWhite rounded-md hover:bg-brand-light text-brand-dark no-underline"
                            href="{{ $url }}">{{ $page }}</a>
                    @endif
                @endforeach
            @endif
        @endforeach

        {{-- Next Page Link --}}
        @if ($paginator->hasMorePages())
            <a class="pagination rounded-r rounded-sm border border-solid border-darkGray px-3 py-2 bg-baseOrange hover:bg-brand-light text-brand-dark no-underline"
                href="{{ $paginator->nextPageUrl() }}" rel="next">&raquo;</a>
        @else
            <span
                class="rounded-r rounded-sm border border-solid border-darkGray px-3 py-2 bg-baseGray hover:bg-brand-light text-brand-dark no-underline cursor-not-allowed">&raquo;</span>
        @endif
    </div>
@endif
0 likes
1 reply
vincent15000's avatar

I think you need to send the current page to display.

You can see in the documentation that the page variable doesn't exist.

{
   "total": 50,
   "per_page": 15,
   "current_page": 1,
   "last_page": 4,
   "first_page_url": "http://laravel.app?page=1",
   "last_page_url": "http://laravel.app?page=4",
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "path": "http://laravel.app",
   "from": 1,
   "to": 15,
   "data":[
        {
            // Record...
        },
        {
            // Record...
        }
   ]
}

https://laravel.com/docs/9.x/pagination#paginating-query-builder-results

1 like

Please or to participate in this conversation.