Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Auto Load More Data on Page Scroll using AJAX Tutorial

Last Updated on May 10, 2024 by

Auto Load More Data is a technology that helps users to automatically get data from the server with the help of Ajax when they scroll down the page in laravel 11 applications.

Here, I will create an example of auto loading more data on page scroll using jquery ajax:

Step 1: Create Routes

Create routes in routes/web.php file to handle auto load more page scroll requests on server:

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;
   
    
Route::get('posts',[PostController::class,'index'])->name('posts.index');

Step 2: Create Controller and Method

Create controller file by using the following command:

php artisan make:controller PostController

And create method in PostController.php controller file to handle dynamic data from database:

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
     
class PostController extends Controller
{
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $posts = Post::paginate(10);
  
        if ($request->ajax()) {
            $view = view('data', compact('posts'))->render();
  
            return response()->json(['html' => $view]);
        }
  
        return view('posts', compact('posts'));
    }
}

Step 3: Create View File

Create a view file in resources/views folder to show page and data on it:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 11 Load More on Scroll Example - ITCODSTUFF.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
      
<div class="container mt-5" style="max-width: 750px">
  
    <h1>Laravel 11 Load More on Scroll Example - ITCODSTUFF.com</h1>
  
    <div id="data-wrapper">
        @foreach ($posts as $post)
     <div class="card mb-2"> 
       <div class="card-body">{{ $post->id }} 
        <h5 class="card-title">{{ $post->title }}</h5>
        {!! $post->body !!}
    </div>
</div>
@endforeach
    </div>
  
    <!-- Data Loader -->
    <div class="auto-load text-center" style="display: none;">
        <svg version="1.1" id="L9" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            x="0px" y="0px" height="60" viewBox="0 0 100 100" enable-background="new 0 0 0 0" xml:space="preserve">
            <path fill="#000"
                d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">
                <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s"
                    from="0 50 50" to="360 50 50" repeatCount="indefinite" />
            </path>
        </svg>
    </div>
</div>
  

</body>
</html>

Step 4: Implement Ajax Code

Implement AJAX code to load more data dynamically as the user scrolls down on page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    var ENDPOINT = "{{ route('posts.index') }}";
    var page = 1;
  
    /*------------------------------------------
    --------------------------------------------
    Call on Scroll
    --------------------------------------------
    --------------------------------------------*/
    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() >= ($(document).height() - 20)) {
            page++;
            infinteLoadMore(page);
        }
    });
  
    /*------------------------------------------
    --------------------------------------------
    call infinteLoadMore()
    --------------------------------------------
    --------------------------------------------*/
    function infinteLoadMore(page) {
        $.ajax({
                url: ENDPOINT + "?page=" + page,
                datatype: "html",
                type: "get",
                beforeSend: function () {
                    $('.auto-load').show();
                }
            })
            .done(function (response) {
                if (response.html == '') {
                    $('.auto-load').html("We don't have more data to display :(");
                    return;
                }
  
                $('.auto-load').hide();
                $("#data-wrapper").append(response.html);
            })
            .fail(function (jqXHR, ajaxOptions, thrownError) {
                console.log('Server error occured');
            });
    }
</script>

Step 5: Test This Application

Run php artisan command to start application server:

php artisan serve

Test your application by running this application on browser and scrolling down the page to see if more data loads automatically.

Leave a Comment