The Infinite Scroll feature is malfunctioning when the $(window).scrollTop() is greater than or equal to $(document).height() - $(window).height() - 10

JavaScript:

$.ajax({
        type: 'POST',
        url: 'getcontent.php',
        data: 'lastid=' + 0,
        dataType: "html",
        success: function (data) {
            console.log(data);
            $("#content").append(data);
        }
    });

    $(window).scroll(function () {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
            var last_id = $(".entries:last").attr("id");
            loadMoreData(last_id);
        }
    });

    function loadMoreData(last_id) {
        $.ajax({
            type: 'POST',
            url: 'getcontent.php',
            data: 'lastid=' + last_id,
            dataType: "html",
            success: function (data) {
                console.log(data);
                $("#content").append(data);
            }
        });
    }

PHP:

<?php
include_once("Medoo.php");

use Medoo\Medoo;

$database = new Medoo([
    'database_type' => 'sqlite',
    'database_file' => 'db.db'
]);

$lastid = $_POST['lastid'];
//$lastid = 10;
$lastid += 1;
$html = "";
$content = $database->select("entries", ["id", "entry"], ["id[<>]" => [$lastid, $lastid + 9]]);

for ($i = 0; $i < count($content); $i++) {
    $html .= "<p class='entries' id='" . $content[$i]["id"] . "'>" . $content[$i]["entry"] . "</p>";
}
echo $html;
?>

HTML:

<html>
<head>
<style>

p {
    width: 200px;
    height: 100px;
    background-color: aqua;
}

</style>
</head>
<body>
<div id="content"></div>
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous">
</script>
<script src="getcontent.js"></script>
</body>
</html>

The issue I'm facing is with the infinite scroll functionality. Instead of loading only one block of data, jQuery loads all entries when scrolled down. However, I suspect that this line might be causing the problem:

$(window).scrollTop() >= $(document).height() - $(window).height() - 10

I have tried various solutions from tutorials and fiddles, but none seem to work effectively. The PHP file seems to be returning the expected 10 objects from the database.

Answer №1

This is the correct code to determine if document.body.offsetHeight is less than window.innerHeight + document.body.scrollTop + 100

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to calculate the time difference between two H:i times using a 24-hour clock?

I'm currently working on a project that involves calculating fees based on the duration of events that sometimes extend into the early hours of the next day. Within my database, I have a table with data formatted like this to represent event times: ...

limit stop choice

I'm working on modifying a script to limit the number of selections that can be made. Specifically, I want it to stop allowing selections once the total selected items reach or exceed 4. http://jsfiddle.net/dw6Hf/51/ $(function() { $(".selectabl ...

Using Laravel Dingo to fetch data from various database tables

Attempting to extract data from two related tables with a one-to-many relationship, I aim for it to be returned in one response for simultaneous display. However, I find myself unsure of how to return an expanded object correctly. Currently, this is what m ...

Unable to display search results with AJAX in Select2

I'm struggling with getting the desired outcomes to display in Select2 when using AJAX. Below is my code: $(document).ready(function() { $("#producto").select2({ placeholder: 'Select a product', formatResult: productForm ...

Retrieve column names from a table that match a specific pattern by utilizing a query with PDO

Is there a way to retrieve the names of all columns that follow a specific pattern? For instance, retrieving all columns that begin with 'allow'. I prefer to achieve this using only a pure PDO query rather than relying on a PHP array filter. $qu ...

Steps for Embedding an HTML Page into a Tab using jQuery

Within the tab labeled class=plots-tabs-heatmap, I am attempting to insert a new page using the code below. However, instead of seeing tmpdata/page2.html displayed on the tab, nothing appears. $('#plots-tabs-heatmap').html("tmpdata/page2.html"); ...

Client-side validation with JQuery for a custom attribute

I recently developed a unique Custom Validation Attribute: public sealed class DateValidatorAttribute : DataTypeAttribute { /// <summary> /// Constructor for the DateValidator Attribute. /// </summary> publi ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

What methods can be used to reduce the number of dependencies passed to a controller effectively?

Trying to streamline my Silex code, I am working on removing the $app parameter from my controller actions and only passing in the necessary dependencies. Typically, my controllers rely on these common dependencies: Template engine Session provider Tran ...

Updating the text box's font color to its original black shade

I have a form that includes dynamic text boxes fetching data from the backend. When a user clicks on a text box, the color of the text changes. Upon form submission, a confirmation message is displayed and I want the text box color to revert back to black. ...

Employing AJAX to send form data to a pair of destinations

Can anyone help me out? I am having trouble using AJAX to submit my form to one location and then to another. Once it's posted to the second location, I want it to send an email with PHP to a specified recipient, but for some reason, it's not wor ...

Is it possible to adjust the range of a range slider based on the selection of a radio button or other input method?

I have a query and I’m hopeful you can assist: function UpdateTemperature() { var selectedGrade = $( "input[name='radios']:checked" ).val(); $( ".c_f" ).text(selectedGrade); var value1 = $("#tempMin").val(); var value2 = $("#tempM ...

Scraping Websites with SimpleHTMLDom in PHP

I am struggling to extract specific data from a table on a website page, particularly the columns name, level, and experience. The table's alternating row colors (zebra pattern) are complicating this task. I have implemented SimpleHTMLDom for this pu ...

"Exploring the Dynamic Duo: Ajax_JQUERY and the Power of

I am a beginner in Laravel and I'm looking to include edit and show buttons in the Controller using my controller below <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class LiveSearch extends Contr ...

Load data from a JSON flat file and dynamically populate new <li> elements with it

I'm attempting to utilize data from a json flat file in order to: Create new list items Fill specific classes within the newly created list items The json data appears as follows: { "event": { "title": "Title of event", "preface": "Prefa ...

What is the process for filtering by condition on a JSON column in MySQL?

What is the best way to construct a query for selecting data based on a where condition from a column containing a JSON array? For example, let's say I have a table called ci_sessions with columns user_name, user_role, and user_data which is stored as ...

Utilizing jQuery for displaying or hiding list elements

To view all the code, click on this link: http://jsfiddle.net/yrgK8/ A section titled "news" is included in the code snippet below: <ul id="news"> <li><p>asfdsadfdsafdsafdsafdsafdsafdsafdsa</p></li> <li>&l ...

Ways to Press the Enter Key on Different Browsers

Looking for a solution to get the keypress action working properly? I have a chat feature where I need to send messages. Here is what I have in the Form-tag (JSP based): function SendMessage() { if (event.keyCode===13) { ale ...

How can you eliminate the escaping slash returned by PHP's PDO?

When using PDO for select queries, I noticed that the result fetched contains escaped single quotes, appearing as \' instead of just '. Is there a way to prevent this escaping from happening? ...

Steps to create a toggle click event

I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...