qwewq's avatar
Level 1

Why does the ajax pagination not work without page reload?

Hello! I'm using laravel 9 with bootstrap. I've been told that in laravel 9 we need to change the code of AppService Provider to make it work with bootsrap. I did that:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}

I checked the code of controller, web.php, blade files. I think it's okay.

My Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

class PaginationController extends Controller
{
    function index()
    {
     $data = DB::table('posts')->simplePaginate(5);
     return view('pagination', compact('data'));
    }

    function fetch_data(Request $request)
    {
     if($request->ajax())
     {
      $data = DB::table('posts')->simplePaginate(5);
      return view('pagination_data', compact('data'))->render();
     }
    }
}
?>

web.php:

<?php

use App\Http\Controllers\PaginationController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// Route::get('/', function () {
//     return view('welcome');
// });
Route::get('/', [PaginationController::class, 'index']);
Route::get('pagination/fetch_data', [PaginationController::class, 'fetch_data']);

welcome.blade.php:

            <section class="discounts">

                <div class="grid">

                    <div>
                        <span class="aside-block">от 40%</span>
                        <h1 class="discounts">Скидки</h1>
                    </div>
                        {!! $discounts->links() !!}
                        {{-- {!! $discounts->links('vendor.pagination.small-arrows') !!} --}}
                </div>


                <article class="">
                    <div class="slider">
                        @include('pagination_discounts')
                    </div>


                  ///...

            </section>

pagination_discounts.blade.php:

`` @foreach ($discounts as $discount)

{{ $discount->name }}

-{{ $discount->discount }}% {{ $discount->cost }}$
@endforeach ```

And yes, I use my custom arrows,

@if ($paginator->hasPages())
    <nav role="navigation" aria-label="Pagination Navigation" class="flex justify-between small_arrows">
        {{-- Previous Page Link --}}
        @if ($paginator->onFirstPage())
            {{-- <span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default leading-5 rounded-md">
                {!! __('pagination.previous') !!}
            </span> --}}
        <a class="arrow left not-allowed"></a>
        @else
            {{-- <a href="{{ $paginator->previousPageUrl() }}" rel="prev" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-gray-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150">
                {!! __('pagination.previous') !!}
            </a> --}}
            <a href="{{ $paginator->previousPageUrl() }}" class="arrow left"></a>
        @endif

        {{-- Next Page Link --}}
        @if ($paginator->hasMorePages())
            {{-- <a href="{{ $paginator->nextPageUrl() }}" rel="next" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 rounded-md hover:text-gray-500 focus:outline-none focus:ring ring-gray-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150">
                {!! __('pagination.next') !!}
            </a> --}}
            <a href="{{ $paginator->nextPageUrl() }}" class="arrow right"></a>
        @else
            {{-- <span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 cursor-default leading-5 rounded-md">
                {!! __('pagination.next') !!}
            </span> --}}
            <a class="arrow right not-allowed"> </a>
        @endif
    </nav>
@endif

At the top of my JS:

    
    $(document).on('click', '.discounts .small_arows a', function(event){
     event.preventDefault(); 
     var page = $(this).attr('href').split('page=')[1];
     fetch_data(page);
    });
   
    function fetch_data(page)
    {
     $.ajax({
      url:"/pagination/fetch_data?page="+page,
      success:function(data)
      {
       $('.discounts .slider').html(data);
      }
     });
    }
    
   });

Also I wanted to say that I dont't have any errors in the console and ajax request is sent every time I click on the button "next" or "prev"... But anyway the page reloads everytime I click "next" or "prev".

0 likes
4 replies
vincent15000's avatar

That's strange, I see that you have an event.preventDefault(), so this could stop the reload of the page.

If you add an alert('something') just after the event.preventDefault(), does it reload your page too ?

1 like
jlrdw's avatar

For Ajax pagination just load in an object has worked fine for me.

2 likes
iftekhs's avatar

How about you track your page number using javascript instead of taking that from the query. so add an event listener that listens to the next and previous clicks and records which page is the current page. Then according to that, you query on your database.

2 likes

Please or to participate in this conversation.