Loading content on scroll using Ajax and PHP example. No library needed

Loading content on scroll using Ajax and PHP example. No library needed

Nov 23,2022

Sometimes you need to show more content to the user as he/she scrolls down the page. This can have more benefits like increasing page load performance. Whatever the reason you want to do this we got you covered. Follow these simple steps to achieve it in a lapse of time.

Step I: Create content.php file in in your project at the same level as the page you want to use this functionality. Open the file and paste in the following code:

<?php

$contents = [

    1=>[

        'title'=>"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout",

        'image'=>"https://cdn.r24live.rw/images/medium/1669127605_perimi.jpg"

    ],

    2=>[

        'title'=>"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout",

        'image'=>"https://cdn.r24live.rw/images/medium/1669133014_arton67499-c9afd.jpg"

    ],

    3=>[

        'title'=>"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout",

        'image'=>"https://cdn.r24live.rw/images/medium/1669127605_perimi.jpg"

    ],

    4=>[

        'title'=>"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout",

        'image'=>"https://cdn.r24live.rw/images/medium/1668844691_thumbs-b-c-98dea8ca4d06daf62d054e2d73ab4bf5.jpg"

    ],

    5=>[

        'title'=>"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout",

        'image'=>"https://cdn.r24live.rw/images/medium/1668770770_arton67405-1cd42.jpg"

    ],

    6=>[

        'title'=>"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout",

        'image'=>"https://cdn.r24live.rw/images/medium/1634385128_impenure-2542491596784417.jpg"

    ]

    

];

 

if(isset($_POST)){

    $html = '<div data-class="row">';

    foreach($contents as $item){

        $html.='

            <div data-class="col-lg-4">

                <div data-class="card mb-3">

                <img class="lazy" data-src="'.$item['image'].'" data-class="card-img-top" alt="...">

                    <div data-class="card-body">

                    <h5 data-class="card-title">'.htmlentities($item['title']).'</h5>

                    <a href="#" data-class="btn btn-primary">Read more</a>

                    </div>

                </div>

            </div>

        ';

    }

    $html.='</div>';

    echo $html;

 

}

 

Step: II: Copy the following lines and paste them where you want the loaded content to appear in you page:

<div id="ajaxContent"></div>

<div id="loading" data-class="text-center d-none">Loading...</div>

Step III: Add these javascript code at the bottom of your page before the closing html tag. Remember to wrap them in scrip tag.

    /**Wait until the dom is full loaded**/

    document.addEventListener("DOMContentLoaded", function () {

        // Listen as user scroll down the document 

        window.addEventListener('scroll',onScrollHandler);

        console.log(document.body.scrollHeight);

    });

    function onScrollHandler(e){

        /**where the content will be appended**/

        var ajaxContentContainer = document.getElementById('ajaxContent');

        //get the scrolled height

        var scrolledHeight = (window.innerHeight + window.scrollY);

        //if the user scrolled the page at the very bottom point, then load more content

        //You can choose to load content earlier

        if(scrolledHeight == document.documentElement.scrollHeight) {

            loadContent((content)=>{

                //create a div element

                var newContent = document.createElement('div');

                //add the loaded content to the newly created div

                newContent.innerHTML=content;

                //append content to the ajax container for the user to see it

                ajaxContentContainer.append(newContent);

            });

        }

    }

 

    function loadContent(callback){

        //show loading text so that the user can know what is going on

        let loading = document.getElementById('loading');

        loading.classList.remove('d-none');

        //fetch data online

        fetch('content.php',{

            method:'post'

        })

        .then(res=>{return res.text()})

        .then(data=>{

            //hide loading text

            loading.classList.add('d-none');

            if(!data){

                throw "Data was not found";

            }

            else{

                //return data to the calling function

                callback(data);

            }

        })

        .catch(err=>{

            //hide loading text

            loading.classList.add('d-none');

            //log error for developer to se what happened

            console.log(err);

        })

    }

View Demo

Download source Code