article

Friday, August 5, 2022

Laravel Load content on page scroll with jquery ajax

Laravel Load content on page scroll with jquery ajax

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table

Create Dummy Data

php artisan tinker
C:\xampp\htdocs\laravel\laravelproject>php artisan tinker

After opening tinker run the following command for creating dummy records

User::factory()->count(500)->create()

Create Controller

php artisan make:controller UserController 
C:\xampp\htdocs\laravel\laravelproject>php artisan make:controller UserController 

change it with the following codes:
laravelproject\app\Http\Controllers\UserController.php
//laravelproject\app\Http\Controllers\UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public $rowperpage = 4; // Number of rowsperpage

    public function index(){

         // Number of rowsperpage
         $data['rowperpage'] = $this->rowperpage;

         // Total number of records
         $data['totalrecords'] = User::select('*')->count();

         // Fetch 4 records
         $data['users'] = User::select('*') 
                ->skip(0)
                ->take($this->rowperpage)
                ->get();

         // Load index view
         return view('index',$data);
    }

    // Fetch records
    public function getUsers(Request $request){

        $start = $request->get("start");

        // Fetch records
        $records = User::select('*') 
              ->skip($start)
              ->take($this->rowperpage)
              ->get();

         $html = "";
         foreach($records as $record){
              $id = $record['id'];
              $name = $record['name'];
              $email = $record['email'];

              $html .= '<div class="card w-75 post">
                    <div class="card-body">
                         <h5 class="card-title">'.$name.'</h5>
                         <p class="card-text">'.$email.'</p>
                    </div>
               </div>';
          }

          $data['html'] = $html;

          return response()->json($data);

   }
}
Create Views
laravelproject\resources\views\index.blade.php

Bootstrap 5 https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
//laravelproject\resources\views\index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Load content on page scroll with jquery ajax</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<style type="text/css">
.card{
    margin: 0 auto;
    margin-top: 35px;
}
</style>
</head>
<body>
<div class='container'> <p><h2>Laravel Load content on page scroll with jquery ajax</h2></p>
    @foreach($users as $rs)
        @php
        $id = $rs['id'];
        $name = $rs['name'];
        $email = $rs['email'];
        @endphp
        <div class="card w-75 post">
            <div class="card-body">
                <h5 class="card-title">{{ $name }}</h5>
                <p class="card-text">{{ $email }}</p>
            </div>
        </div>
    @endforeach
    <input type="hidden" id="start" value="0">
    <input type="hidden" id="rowperpage" value="{{ $rowperpage }}">
    <input type="hidden" id="totalrecords" value="{{ $totalrecords; }}">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">

    checkWindowSize();

    // Check if the page has enough content or not. If not then fetch records
    function checkWindowSize(){
        if($(window).height() >= $(document).height()){
            // Fetch records
            fetchData();
        }
    }

    // Fetch records
    function fetchData(){
        var start = Number($('#start').val());
        var allcount = Number($('#totalrecords').val());
        var rowperpage = Number($('#rowperpage').val());
        start = start + rowperpage;

        if(start <= allcount){
            $('#start').val(start);

            $.ajax({
                url:"{{route('users.getUsers')}}",
                data: {start:start},
                dataType: 'json',
                    success: function(response){
                    // Add
                    $(".post:last").after(response.html).show().fadeIn("slow");

                    // Check if the page has enough content or not. If not then fetch records
                    checkWindowSize();
                }
            });
        }
    }

    $(document).on('touchmove', onScroll); // for mobile
       
        function onScroll(){
             if($(window).scrollTop() > $(document).height() - $(window).height()-100) {
                   fetchData(); 
             }
        }

        $(window).scroll(function(){
             var position = $(window).scrollTop();
             var bottom = $(document).height() - $(window).height();

             if( position == bottom ){
                   fetchData(); 
             }
        });
</script>
</body>
</html>
Route
laravelproject\routes\web.php
//laravelproject\routes\web.php
<?php

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

/*
|--------------------------------------------------------------------------
| 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('users', [UserController::class, 'index']);
Route::get('users/getUsers', [UserController::class, 'getUsers'])->name('users.getUsers');
Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post