Load Content on Page Scroll Using PHP, jQuery, and AJAX

Last updated 2 weeks, 5 days ago | 34 views 75     5

Tags:- PHP Ajax PHP-MySQL

Infinite scrolling or scroll-based content loading is a modern technique used to enhance user experience by loading more content as the user scrolls down the page — popularized by social media platforms like Facebook, Twitter, and Instagram.

In this article, you'll learn how to build an infinite scroll feature using PHP, jQuery, and AJAX.


Tools & Technologies

  • Frontend: HTML, CSS, jQuery

  • Backend: PHP

  • Database: MySQL (Example)

  • AJAX: For asynchronous data fetching


Step-by-Step Implementation


1. Database Setup

Let’s assume we have a posts table:

CREATE TABLE posts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  content TEXT NOT NULL
);

Insert dummy data:

INSERT INTO posts (title, content)
VALUES 
('Post 1', 'This is the content of post 1'),
('Post 2', 'This is the content of post 2'),
-- repeat for 20+ rows
('Post 20', 'This is the content of post 20');

2. HTML + jQuery + AJAX (Frontend)

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Infinite Scroll with PHP and AJAX</title>
    <style>
        .post { border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; }
        #loading { display: none; text-align: center; padding: 20px; }
    </style>
</head>
<body>
    <div id="post-container"></div>
    <div id="loading">Loading more posts...</div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        let limit = 5;
        let start = 0;
        let action = 'inactive';

        function load_posts(limit, start) {
            $.ajax({
                url: "load_posts.php",
                method: "POST",
                data: { limit: limit, start: start },
                cache: false,
                beforeSend: function() {
                    $('#loading').show();
                },
                success: function(data) {
                    $('#post-container').append(data);
                    $('#loading').hide();
                    if (data === '') {
                        action = 'active';
                    } else {
                        action = 'inactive';
                    }
                }
            });
        }

        if (action === 'inactive') {
            action = 'active';
            load_posts(limit, start);
        }

        $(window).scroll(function() {
            if ($(window).scrollTop() + $(window).height() > $("#post-container").height() && action === 'inactive') {
                action = 'active';
                start += limit;
                setTimeout(function() {
                    load_posts(limit, start);
                }, 500);
            }
        });
    </script>
</body>
</html>

3. PHP Backend (load_posts.php)

<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "your_database";

$conn = new mysqli($host, $user, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$limit = intval($_POST["limit"]);
$start = intval($_POST["start"]);

$sql = "SELECT * FROM posts ORDER BY id ASC LIMIT $start, $limit";
$result = $conn->query($sql);

$output = '';

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $output .= '
        <div class="post">
            <h3>' . htmlspecialchars($row["title"]) . '</h3>
            <p>' . nl2br(htmlspecialchars($row["content"])) . '</p>
        </div>
        ';
    }
}

echo $output;
?>

✅ Complete Code Example Structure

Project Files:

/project-root
├── index.html
├── load_posts.php
└── database with `posts` table

Tips & Best Practices

  1. Pagination Limit: Adjust the limit value based on your performance testing. Start small (e.g., 5 or 10).

  2. Debounce Scroll Events: Add a small delay (as shown with setTimeout) to avoid multiple simultaneous AJAX calls.

  3. Security: Always sanitize and validate inputs (limit, start) to avoid SQL injection.

  4. Loading Indicator: Always provide user feedback (e.g., a loader) during content loading.

  5. Error Handling: Include error: in AJAX for better debugging.

error: function(xhr, status, error) {
    console.error("AJAX Error:", status, error);
}

⚠️ Common Pitfalls

  • Not stopping AJAX calls at the end of content: If the server returns an empty response, set a flag (action = 'active') to stop further calls.

  • Hardcoding values: Avoid hardcoding database credentials or paths. Use configuration files or environment variables.

  • Ignoring Mobile Performance: Optimize DOM updates and image loading for mobile users.


Conclusion

With the combination of PHP, jQuery, and AJAX, infinite scrolling can be implemented effectively to enhance UX. Always test on different screen sizes and internet speeds to ensure your implementation is smooth and responsive.