How To Load More Data on Page Scroll Using Ajax Jquery Laravel 11?

Jun 15, 2024 | Laravel 11 Laravel


Hello Dev,

This example focuses on implementing auto-loading more data on page scroll in Laravel 11 using AJAX. You'll learn how to dynamically load additional content as the user scrolls down a web page, enhancing the user experience.

Auto-loading more data on page scroll with AJAX is a technique used to seamlessly load additional content as users scroll down a web page. It's particularly beneficial for pages with large amounts of data or content fetched from a remote server. This technique utilizes Asynchronous JavaScript and XML (AJAX) to fetch additional data from the server without needing to refresh the page. When the user reaches the bottom of the page, JavaScript detects this event and sends an AJAX request to the server for more data. The response is then appended to the existing content, providing a seamless browsing experience without requiring the user to click on a "next page" button or wait for a page refresh.

Implementing this technique can enhance page performance by reducing initial data loading and improving page load times. It also offers a more engaging user experience by eliminating the need to navigate between multiple pages or wait for content to load.

In this example, we'll start by creating a posts table using migration. Then, we'll establish a data model for posts and a factory class to generate dummy post data. Finally, we'll create a route to load posts and implement the code for auto-loading more data on page scroll using AJAX. Let's delve into this step-by-step example.

Step 1: Install Laravel 11

If you haven't already, create a new Laravel project:

composer create-project laravel/laravel example-app
Step 2: MySQL Database Configuration .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Create Migration

Here, we'll create a new migration to add a new table named "posts" in the database. Let's execute the following command:

php artisan make:migration create_posts_table

After executing this command, you'll find a file in the "database/migrations" directory. In this file, you'll need to add the following code to create the "products" table.

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Now, run this migration by following command:

php artisan migrate
Step 4: Create Model

After creating the "posts" table, you should create a Post model for handling posts. First, create a file in the path "app/Models/Post.php" and add the following content to the Post.php file:

app/Models/Post.php
<?php
    
namespace App\Models;
    
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
    
class Post extends Model
{
    use HasFactory;
   
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'body', 'slug'
    ];
}
Read Also: Laravel 11 Custom Validation Error Message Example Tutorial Step 5: Create Factory Class

This step demonstrates how to generate dummy data using a factory. This data will be dynamically loaded on page scroll.

php artisan make:factory PostFactory --model=Post
database\factories\PostFactory.php
<?php
    
namespace Database\Factories;
    
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
use Illuminate\Support\Str;
    
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;
      
    /**
     * Define the model's default state.
     *
     * @return array

     */
    public function definition(): array
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'body' => $this->faker->paragraph()
        ];
    }
}

Open terminal, execute the below commands to generate the test data:

php artisan tinker
Post::factory()->count(20)->create()
Step 6: Create Route

In this step, let's create routes for displaying posts and fetching posts. Open your "routes/web.php" file and add the following routes.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;
   
/*
|--------------------------------------------------------------------------
| 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('posts',[PostController::class,'index'])->name('posts.index');
Step 7: Create Controller

Here, we need to create a new controller named PostController with an index method to display the posts view and return data. Let's add the following code.

app/Http/Controllers/PostController.php
<?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'));
    }
}
Read Also: How to Create a Custom Validation Rule in Laravel 11? Step 8: Create View File

In the final step, let's create posts.blade.php and data.blade.php to display the list of posts. Below is the code for both files.

resources/views/posts.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>How To Load More Data on Page Scroll Using Ajax Jquery Laravel 11? -- ItErrorSolution.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">
</head>
<body>
      
<div class="container mt-5" style="max-width: 750px">
  
    <h1>How To Load More Data on Page Scroll Using Ajax Jquery Laravel 11? -- ItErrorSolution.com</h1>
  
    <div id="data-wrapper">
        @include('data')
    </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>
  
<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>
</body>
</html>
resources/views/data.blade.php
@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>
Step: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/posts
Output:
How To Load More Data on Page Scroll Using Ajax Jquery Laravel 10?

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"