What is the best way to implement ajax loading on scroll?

I need to implement lazy loading for multiple ajax pages on my website. I want the ajax content to load dynamically as the user scrolls down the page, similar to infinite scroll or lazy image loading.

$('.lazy_content').on('load', function (e) {

            data_url = $(this).attr("data-url");
            data_id = $(this).attr("data-target-id");

            $.ajax({
                url: data_url,
                type: "POST",
                beforeSend: function () {
                    $(".loaderDiv").show();
                    $("#" + data_id).html("");
                },
                success: function (data) {
                     $(data).each(function(index, el) {
                    $(".loaderDiv").hide();
                    $("#" + data_id).html(data);
               });
                }

            })

        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lazy_content" data-url="/ajax/comments/aurum-didyma-spa-beach-resort" data-target-id="comments-content">
  <h4>COMMENTS</h4>
  <div id="comments-content" class="content-target"></div>
</div>

Answer №1

To implement infinite scrolling, simply include the following event listener on the specified element (div):

 $('.lazy_content').scroll(function() {
      data_url = $(this).attr("data-url");
      data_id = $(this).attr("data-target-id");

      $.ajax({
           url: data_url,
           type: "POST",
           beforeSend: function () {
                $(".loaderDiv").show();
                $("#" + data_id).html("");
           },
           success: function (data) {
                $(data).each(function(index, el) {
                     $(".loaderDiv").hide();
                     $("#" + data_id).html(data);
                });
           }
      })
 });

Answer №2

There is a specific JavaScript event designed for this:


    onscroll="determineScroll"

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

jinja2.exceptions.TemplateSyntaxError: anticipated symbol indicating 'end of block statement', received 'text'

{% extends "base.html %} {% block content %} <h1 style="text-align: center">Displaying Owner Information</h1> <fieldset align="centre"> <body> {% for value in p %} {{ value.id }}<br> {{ value.start_location ...

NodeJS Implementation of Faye Websocket

I'm diving into the world of nodeJS and faye / websockets. I've created a datatable using webix and now I want to implement live updates to it. Currently, I am experimenting with Faye, but I'm unsure about what steps to take after receivin ...

Learn how to efficiently pass multiple props using a loop in Vue

I am dealing with an object that has multiple properties. Typically, I know which props I want to pass to my component and do it like this: <component :prop1="object.prop1" :prop2="object.prop2" :prop3="object.prop3" /> However, I want to pass the ...

Problems with refreshing Asp.net MVC WebGrid in partial view with Ajax are frustrating

I am currently facing an issue with 2 WebGrids that are displayed in separate partial views on a view page. Everything seems to be working fine, but when I try to sort or paginate the WebGrids, the updates are not happening through ajax. Can someone help m ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

What could be the reason for my array parameter not being included in the POST request

When working on my laravel 5.7 / jquery 3 app, I encountered an issue while trying to save an array of data. After submitting the form, I noticed that only the _token parameter is being sent in the POST request as seen in the browser console: let todos_co ...

How can CSS be used to create a responsive form script?

We have enlisted the services of an SEO provider through upcity.com, which necessitates us to embed a form on our website. However, we are facing challenges with the responsiveness of the form on mobile devices, which undermines our efforts. Therefore, I a ...

Adjust the size of text with jQuery to make it larger or smaller

I run a news website and I'm looking to add buttons that allow users to increase or decrease the font size of the page. I have set a default text size in CSS like this: <style> * { font-size: 12px ; } </style ...

Stop a hacker from obtaining the usernames from a system

Our forgot password page has been identified with a security issue that needs attention: ISS-0003938 Web Inspect Open Medium Suspicious Files Found in Recursive Directory ****** Remove any unnecessary pages from the web server If any files are nec ...

How can I implement $compile to execute a function on every row using angularjs and razor?

UPDATE: It seems that there is some confusion here, I am looking to apply the function to all rows, without using '', "", '"... After conducting some research, I have discovered that I will need to utilize $compile, but I am ...

What is the process for transferring a JavaScript variable to a Java servlet?

I am trying to send a JavaScript variable to a Java servlet in a web application I am developing. Below is the HTML code: <p id="test">Some text</p> Here is the JavaScript code I am using: var myVar = document.getElementById('test' ...

Both JOINs are being performed on the identical table

Currently, I am working on a website that displays soccer scores with two teams and two scores stored in my database. Below is the code I am using: <?php $result = mysql_query( "SELECT * FROM resultat LEFT JOIN brukere ON resultat.do ...

Hide Bootstrap Modal and display another one after an ajax request is made

Currently, in my project, I am using Asp core 3.1 and implementing data saving with ajax through a bootstrap modal. Even though the data is successfully saved, the modal does not hide upon success. Additionally, I am trying to display another modal with fe ...

What is the process for customizing the user interface of modules in Apache OFBiz?

For the past month, I have been immersed in working on Apache ofbiz (17.12.07) and have developed a custom UI requirement for a client. My goal is to incorporate a side-bar (see screenshot attached below) into all ofbiz modules. To achieve this, I created ...

Determine username availability using Jquery, Ajax, in combination with Flask and a Sqlalchemy database

Struggling with using Jquery and Ajax to verify the availability of a username. Despite checking the code multiple times, the loading image appears but the username messages do not show up, and even the loading image doesn't get hidden. Please assist ...

The function in PHP does not arbitrarily return a boolean value

After creating a template file for WordPress, I encountered an issue with a function that I wrote. Despite ensuring that the two variables are different (as I confirmed by printing them), the function consistently returns true. Even after testing and attem ...

Transfer all image files from Node.js to the frontend

What is the best way to send all image files from my backend nodejs server folder to my Reactjs client? I have set up a website where users can sign in and upload their files. However, I am facing an issue where only one file is visible on the client side, ...

Right now, I am sending out 3 GET requests for JSON files using Axios. I wonder if they are being loaded simultaneously or one after the other

In the process of developing my application, I am loading 3 JSON files to gather information about a game's characters, spells, and more. As of now, I have implemented 3 functions that utilize axios to make GET requests and store the responses. Howeve ...

The secondary angular button is failing to execute the function

Can someone help me with a small issue? I have two buttons on a webpage that should both contact a server. However, only the first button sends a HTTP request when clicked. <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8 ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...