implementing automatic ajax requests when user scrolls

This is a piece of JavaScript code:

 $(window).scroll(function() {
         $.ajax({
            type: "GET",
            url: "not_data.php",
            data: dataString,
            success: function my_func () {
               //show new name
            }
        });
      });

The file this script is calling is not_data.php

<?php

$name_query=mysql_query("SELECT name FROM  names");
        while($run_query = mysql_fetch_assoc($name_query)) {
            $name = $run_query['name'];

            echo $name;
}
?>

The goal here is to trigger a new AJAX request and retrieve a fresh name from the 'names' table each time a user scrolls down.

Answer №1

Check out this amazing jquery plugin I found!

Unlimited Scrolling is a fantastic jQuery plugin for endless scrolling, created by Sarah Johnson. Endless scrolling, also referred to as dynamic loading, continuous scrolling, and never-ending pages, allows you to dynamically load content via AJAX as you scroll down the page. The new content can be seamlessly loaded each time you reach the bottom of the current content, or you can manually trigger it by clicking a link at the end of the existing content.

Answer №2

Define a parameter to monitor the loading state; Attach it to the scroll event Retrieve two parameters

var currentPosition = $(this).scrollTop();
var elementHeight = $(this).height();

Check the scrolling height

if (elementHeight - currentPosition - elementHeight <= 50) 

where elementHeight represents the total height of the element

If this condition is met, proceed with your query

Answer №3

Give this method a try.

$(window).scroll(function() {
    if( $(window).scrollTop() == $(document).height() - $(window).height()) {
        $.ajax({
        type: "GET",
        url: "fetch_data.php",
        data: dataString,
        success: function (result) {
           // The response will be stored in variable 'res' for you to display as needed.
        }
        });
    }
});

Answer №4

Ensure you've reached the end of the page and trigger a load more function via ajax

var win = $(window),
    doc = $(document);

win.scroll(function(){
    if( win.scrollTop() > doc.height() - win.height() ) {
        $.ajax({
            type: "GET",
            url: "additional_data.php",
            data: additionalDataString,
            success: function handle_response (response) {
                $('<span>').html(response).appendTo('body')
            }
        });
    }
});

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

Experiencing an issue in Test Cafe when attempting to click on an invisible link using the Client Function

I need to find a way to click on an invisible button in HTML. I attempted to use ClientFunction, however I encountered an error related to the element. import { Selector,ClientFunction } from 'testcafe'; fixture('Clicking Invisible link&apo ...

Update the value after verifying the element

I am trying to retrieve data from my database and update the values when an element is clicked (accepting user posts). The code I have written seems to work, but I encounter an error stating that props.actions is not a function when clicking on an element. ...

Why is this text appearing twice on my screen?

When I run the code in my React app and check the console in Chrome, I notice that the response.data[0] is being printed twice. What could be causing this duplication? const fetchData = async () => { return await axios.get(URL) .then((respon ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

What are alternative methods for reading JSON files in PHP that do not involve file_get_contents()?

Recently, I developed a basic PHP script that fetches data from a local JSON file and uses it to respond to various queries directed at the page. In my implementation, I adopted the usage of file_get_contents() for reading the file. However, as the number ...

"Converting domain names with punycode and utilizing Firebase for a

My current project involves updating a Firebase app with NextJS, and I've encountered an issue that needs to be resolved. Upon running the command: % npm run build I received the following message: (node:3719) [DEP0040] DeprecationWarning: The `pun ...

TypeScript struggling to recognize specified types when using a type that encompasses various types

I have a defined type structure that looks like this: export type MediaProps = ImageMediaProps | OembedProps; Following that, the types it references are defined as shown below: type SharedMediaProps = { /** Type of media */ type: "image" | "oembed"; ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

Importing PHP backend variables into ReactJS with the help of webpack

Is there a way to pass a PHP backend variable into my ReactJS (using react-router) application via Webpack? I'm interested in accomplishing something like this: <?php if ($us->inGroup('Admin')) { ?> <script> var ...

Using Ember's transitionTo method and setting a controller attribute within a callback

I am working with Ember code to transition to a specific route while also setting controllerAttr1 on 'my.route' Upon transitioning to "my.route" using this.get('router').transitionTo("my.route"), I have set up a callback function that ...

What could be causing my Vue application to not launch after executing `npm run serve`?

These past 24 hours have been a struggle for me. I recently embarked on the journey of learning Javascript, and my choice of JS framework was Vue JS. However, when I run npm run serve, my Vue JS app bombards me with numerous errors that seem to make no se ...

Modifying the display style of error messages in Laravel 5 JSON: A guide

I'm attempting to retrieve Laravel 5 error messages and display them in the error div using AJAX. However, the problem arises when Laravel returns error messages enclosed in square brackets which cannot be accessed. In AJAX, I am able to access succe ...

Running a child process in the browser using Node.js with the help of browserify

Utilizing browserify to enable node.js functionality in the browser, I am attempting to run a child process in my index.js file: var exec = require('child_process').exec; //Checking the installed node version var ls = exec('node -v', f ...

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Alert: The function mysqli_query() requires the first parameter to be of type mysqli, but a string was provided in the file path E:OficinaxampphtdocsFormulario-Oficinalistartecnicas.php on

I am facing an issue with my code Alert: mysqli_query() function is expecting the first parameter to be of type mysqli, but a string was provided in E:\Oficina\xampp\htdocs\Formulario-Oficina\listartecnicas.php on line 6 Additi ...

The PHP function force_download is initiating a download of a file with the given filename, however, it is being referred to as 'file

When using force_download in my code, everything is functioning correctly except for one issue - the downloaded file is named 'file.pdf' instead of 'Daily_delivery_sheet.pdf'. Despite the content of the PDF being accurate, the filename ...

Is there a challenge in setting up a tag search bar similar to Stack Overflow's?

First and foremost, I apologize for the awkwardly phrased question. The issue at hand is that when the tags exceed the container size, the search option becomes hidden. My goal is to have the search bar adjust dynamically, moving everything back inside the ...

Why does Chrome keep retrieving an outdated JavaScript file?

Lately, I've been facing a frustrating issue that I just can't seem to figure out. Every now and then, when I update the JavaScript or CSS files for my website hosted on Siteground, Chrome simply refuses to acknowledge the changes. While other br ...