Displaying additional content with the load more button in JQuery

My script below:

Main page: jQuery code

<script type="text/javascript">
        $(document).ready(function(){
            $("#loadmorebutton").click(function (){
                $('#loadmorebutton').html('<img src="ajax-loader.gif" />');
                $.ajax({
                    url: "loadmore.php?lastid=" + $(".postitem:last").attr("id"),
                    success: function(html){
                        if(html){
                            $("#postswrapper").append(html);
                            $('#loadmorebutton').html('Load More');
                        }else{
                            $('#loadmorebutton').replaceWith('<center>No more posts to show.</center>');
                        }
                    }
                });
            });
        });
    </script>

HTML Code:

<div id="wrapper">
<div id="postswrapper">
<?php 
    $getlist = mysql_query("SELECT * FROM table_name LIMIT 25"); 
    while ($gl = mysql_fetch_array($getlist)) { ?>
         <div class=postitem id="<? echo $gl['id']; ?>"><?php echo $gl['title']; ?></div>
    <?php } ?>
</div>
<button id="loadmorebutton">Load More</button>
</div>
</div>

The loadmore.php page contains;

<?php 
$getlist = mysql_query("SELECT * FROM table_name WHERE id < '".addslashes($_GET['lastid'])."' 
LIMIT 0, 25 LIMIT 10"); 
while ($gl = mysql_fetch_array($getlist)) { ?>
<div><?php echo $gl['title']; ?></div>
<?php } ?>

This script loads the initial 25 items from the database on the main page. Clicking "Load More" will trigger loadmore.php, fetching an additional 10 entries starting from the last loaded ID. The aim is to dynamically hide the "Load More" button when there are less than 25 entries and display it otherwise.

Answer №1

Here is a solution that should meet your needs:

<?php 
    $query = mysql_query("SELECT * FROM table_name LIMIT 25"); 
    while ($row = mysql_fetch_array($query)) { ?>
         <div class=postitem id="<? echo $row['id']; ?>"><?php echo $row['title']; ?></div>
    <?php } 
    if(mysql_num_rows($query) <= 25) { ?>
    <script type="text/javascript">
        $(function(){
             $('#loadmorebutton').hide();
        });
    </script>
    <?php } ?>

Answer №2

<div id="wrapper">
<div id="postswrapper">
<?php 
    $getlist = mysql_query("SELECT * FROM table_name LIMIT 25"); 
    **$counter = 0;**
    while ($gl = mysql_fetch_array($getlist)) { ?>
         <div class=postitem id="<? echo $gl['id']; ?>"><?php echo $gl['title']; ?></div>
         **$counter++;**
    <?php } ?>
</div>
**<?php if ($counter == 24) { ?>
<button id="loadmorebutton">Load More</button>
<?php } ?>**
</div>
</div>

Answer №3

modify your php code to include a count variable

<div id="wrapper"> 
<div id="postswrapper"> 
<?php 
$count=0;
$getlist = mysql_query("SELECT * FROM table_name LIMIT 25"); 
while ($gl = mysql_fetch_array($getlist)) {
 $count++;?> 
<div class=postitem id="<? echo $gl['id']; ?>"><?php echo $gl['title']; ?></div> 
<?php } ?> 
</div> 
<button id="loadmorebutton" value="<? echo $count ?>">Load More</button> 
</div> 
</div>

<script type="text/javascript" > 
        $(document).ready(function(){ 
            $("#loadmorebutton").click(function (){ 
                $('#loadmorebutton').html('<img src="ajax-loader.gif" />'); 
                $.ajax({ 
                    url: "loadmore.php?lastid=" + $(".postitem:last").attr("id"), 
                    success: function(html){ 
                        if(html){ 
                            $("#postswrapper").append(html);                
                            var count = patserInt($('#loadmorebutton').val()); 
                if(count<25){
                        $('#loadmorebutton').html('Load More'); 
                        }else {
                            $('#loadmorebutton').hide();


                        }else{ 
                            $('#loadmorebutton').replaceWith('<center>No more posts to show.</center>'); 
                        } 
                    } 
                }); 
            }); 
        }); 
    </script> 

Answer №4

Here are two choices for you to consider, select the one that is easier for you to understand.

<?php if(25 or more){ ?>
  <button id="loadmorebutton">Load More</button>
<?php } ?>

<?php if(25 or more): ?>
  <button id="loadmorebutton">Load More</button>
<?php endif; ?>

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

Guide to configuring a background image from the public folder in a React application using Create React App

How do I properly set a background image in a .css file located in the src folder? src/Components/Component/Comp.css .services { background-image : url("./images/img-2.jpg"); background-position: center; background-size : cover; b ...

Utilize text wrapping to ensure a fixed maximum height for content display

I am in need of a div that contains text spanning multiple lines, with both a fixed width and a maximum height. Currently, I have applied the CSS property overflow: hidden;. However, my issue arises when the last line of text exceeds the maximum height of ...

Is there a way for me to have a table automatically scrolled to a specific column upon loading the HTML page?

My table contains a dynamic number of columns based on the months inputted from the database starting from a start_date and ending at an end_date. I have the current_date stored as a variable and want the table to load with the x-scrollbar positioned right ...

Combining arrays in Javascript that share the same key by utilizing a loop

Can you advise on the most effective method to restructure an array for desired output? My goal is to combine all key values, whether in arrays or not, into objects with the same name key. Here is my current array: brands: [ 0:ZARA: {product: "ZARA Blac ...

What is the best way to control the class name of elements using jQuery in an MVC4 application?

Among the <li> elements, one of them contains the class "current". Determining which <li> is the current one. View below: @{ int k = 10; //the value changes with each request } <ul class="car"> @foreach (var item in modelCoun ...

Retrieve text from a dropdown menu while excluding any numerical values with the help of jQuery

I am currently implementing a Bootstrap dropdown menu along with jQuery to update the default <span class="selected">All</span> with the text of the selected item by the user. However, my objective is to display only the text of the selected it ...

Utilizing ngModel within the controller of a custom directive in Angular, instead of the link function

Is there a way to require and use ngModel inside the controller of a custom Angular directive without using the link function? I have seen examples that use the link function, but I want to know if it's possible to access ngModel inside the directive ...

Is it considered acceptable to modify classes in a stateless React component by adding or removing them?

My stateless component functions as an accordion. When the container div is clicked, I toggle a couple of CSS classes on some child components. Is it acceptable to directly change the classes in the DOM, or should I convert this stateless component to a ...

Is there a way to integrate datatablejs with AngularJS or are there other options similar to datatablejs that can be

I'm facing a challenge with my application, as I have a large amount of data to generate reports and create data entry forms for users. In the past, I relied on JSON calls from the backend along with datatable.js to manage fixed headers and columns. ...

Resolving problems related to window scrolling in javascript for implementing a "sliding door" style animation triggered by a scroll event

I am new to web development and I have been working on creating a portfolio website to learn. I have seen some websites with really cool effects on their landing pages and I would like to incorporate something similar into my site. Specifically, I am inte ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

What is the best way to reduce the file size of a group of PNG images for

For my game character, I have a collection of PNG files including stand.png, run1.png, run2.png. To display a series of actions on the JavaScript canvas, I need to load these images. However, the size of each .png file adds up quickly – for example, it ...

Toggle the visibility of the route layer in Leaflet by clicking on a button using the Easy Button plugin

I am working on a Leaflet map that includes a button (utilizing the Easy Button plugin from https://github.com/CliffCloud/Leaflet.EasyButton). Upon clicking this button, a route layer is added to the map using the Leaflet Routing Machine plugin (https://gi ...

Center the content of the HTML body

Despite my best efforts, I seem to be making a mistake somewhere. While creating a bootstrap website at , the site appears well and aligned in the center. However, when I try to adjust the screen size to less than 850px or even smaller, all the content shi ...

Discover pictures that perfectly match the optimal container dimensions

Looking to develop a function that can determine the best fitting image based on its size relative to its container. The image should not exceed the dimensions of the container either in width or height. The selected image should have minimal empty space ...

Tips for deactivating pagination indicators on the initial page, final page, as well as on the previous and subsequent pages within Laravel

My goal is to create a pagination disable handler that will effectively disable the first and previous page buttons when I am on the first page, allowing only the next page and last page buttons to be clickable. Similarly, when I am on the last page, the n ...

Why isn't the CSS class being applied to the checkbox element?

I created a basic demo where the HTML markup was the same, but one extra rule was applied in one case and not in the other. Here is the Markup: <div class="rc40w1 oform oform-initialized"> <div class="rc40w5 hide"> < ...

Loading External Content with Jquery Ajax Made Easy

Today marks the beginning of my coding journey with jQuery. I believe that practice is key to learning effectively. My goal is to remove existing content from #container and replace it with new content from an external page. Sounds simple, right? I'v ...

Ways to evaluate two sentences based solely on the spacing in their dynamic sections

I am tasked with comparing two sentences. The first sentence is stored in a database and looks like this: var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd" The second sentence, which comes from the customer, is as follows: &q ...

Utilizing Array.from with a XPathResult: A Comprehensive Guide

In my sample document, I found 138 nodes with the tag td using querySelectorAll. Array.from(document.querySelectorAll('td')).length 138 However, when I tried to do the same using XPath, I did not get any result: Array.from(document.evaluate(". ...