How to Load More Data on Page Scroll by using Ajax Jquery Laravel ?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello dev’s, Now today in this article, I will teach you how to load more data with scroll by using jquery and php Laravel application. Here we don’t have need to click anywhere to load data. Because data is loading on page scroll automatically from our MySQl database table. I will show you How to Load More Data on Page Scroll by using Ajax Jquery Laravel.

It will check if data length is equal to 0 then it display us message for “No more records!” and if data length is more than or equal to one then it append on html data to list.

Here is very Simple example as bellow.

Step 1 : Create Table and Model

Now in this step, we need to create first post table and model.

app/Model/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
public $table = "post";

protected $fillable = [ 'title','description' ];   
}

We need to inserted more dummy records in our post table to see the loader on page scroll.

Step 2: Add Routes

So in this step, we need to add new routes to handle request.

app/Http/routes.php

 Route::get('jquery-loadmore',['as'=>'jquery.loadmore','uses'=>'PostController@jqueryLoadMore']);

Step 3: Create FileController

Now In this step, we need to create a file controller in following path app/Http/Controllers and put bellow code.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\HomeController;
use App\Model\Post;

class PostController extends HomeController
{
    public function jqueryLoadMore(Request $request)
    {
    	$posts=Post::paginate(8);

        $html='';

        foreach ($posts as $post) {
            $html.='<li>'.$post->id.' <strong>'.$post->title.'</strong> : '.$post->description.'</li>';
        }

        if ($request->ajax()) {
            return $html;
        }

    	return view('jqueryLoadmore');
    }
}

Step 4: Create Blade File

That’s now in this step, we will create a new view file within files directory so first create files directory and then create jqueryLoadmore.blade.php directory (resources/views/jqueryLoadmore.blade.php) and put bellow code on file.

resources/views/jqueryLoadmore.blade.php

@extends('layouts.app')
@section('content')
<style>
   .wrapper > ul#results li {
     margin-bottom: 2px;
     background: #e2e2e2;
     padding: 20px;
     width: 97%;
     list-style: none;
   }
   .ajax-loading{
     text-align: center;
   }
</style>
<div class="wrapper">
   <ul id="results"><!-- results appear here --></ul>
   <div class="ajax-loading"><img src="{{ asset('images/loading.gif') }}" /></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
   var page = 1; //track user scroll as page number, right now page number is 1
   load_more(page); //initial content load
   $(window).scroll(function() { //detect page scroll
      if($(window).scrollTop() + $(window).height() >= $(document).height()) { //if user scrolled from top to bottom of the page
      page++; //page number increment
      load_more(page); //load content   
      }
    });     
    function load_more(page){
        $.ajax({
           url: '?page=' + page,
           type: "get",
           datatype: "html",
           beforeSend: function()
           {
              $('.ajax-loading').show();
            }
        })
        .done(function(data)
        {
            if(data.length == 0){
            console.log(data.length);
            //notify user if nothing to load
            $('.ajax-loading').html("No more records!");
            return;
          }
          $('.ajax-loading').hide(); //hide loading animation once data is received
          $("#results").append(data); //append data into #results element          
           console.log('data.length');
       })
       .fail(function(jqXHR, ajaxOptions, thrownError)
       {
          alert('No response from server');
       });
    }
</script>
@endsection

Read Also : Laravel 8 Mobile Number Verification Tutorial

Thanks for read. I hope it help you. For more you can follow us on facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →