2 years ago 2 years ago Javascript Share

How to Make a 'Load More' Button in jQuery and AJAX

This page shows the code for a "Load More" button, using jQuery and AJAX. It can be used to add any content to a <DIV> inside web page while the rest of the page is still loaded.

What is AJAX?

AJAX is basically a means of the client side of an already-loaded web page exchanging data with a server, without having to reload a whole new page. This means it can be used to update parts of a web page — without reloading the whole page.

AJAX is different to (and a lot more sophisticated than) frames or iframes, which require the embedded section to be a separate web page in their own right.

AJAX can be done using plain JavaScript, though it's most commonly implemented through a framework (e.g. jQuery) which makes it a lot easier and simpler.

I'll write another web page sometime later with more details of the basics of AJAX...

How to Use AJAX

To use AJAX to update a section of a web page, this is what you need:

  • Assuming that you're using a framework (e.g. jQuery), to load the script for the framework.
  • A <DIV> somewhere on the main web page which will receive the new content.
  • An event listener (or some other trigger) set up which will give the signal to load the new content. This is done with JavaScript.
  • Code inside the event listener which is triggered by the above event, which loads the new content. This is also done in JavaScript.
  • A new "web page" which will be loaded into the <DIV> inside the main web page.
  • You will probably also want some means of communication between the main/containing web page and the inner <DIV> "web page" being loaded with AJAX. Using session variables in a server-side scripting language (e.g. PHP) is one way of doing this.

An Implementation of a "Load More Results" button using jQuery and AJAX

Following the above set of dot points roughly in order, here a skeleton outline of some code, with descriptions. The main JavaScript file is the actual .js file which is used on this website for the "Show More Results" button, to load more results in the category list pages — e.g. like this.

First load the jQuery library somewhere on the main web page:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Next, name a <DIV> (or create a new <DIV>) in the main/containing web page which will receive the embedded AJAX content:

<div id="listing-more-html" class="optionally-some-class-perhaps"> Optional HTML Content here </div>

It is the id attribute of this <DIV> tag (here it's called "listing-more-html") which the JavaScript AJAX code will use to identify the <DIV>. You can call this id anything you like as long as it matches the AJAX code (shown below).

Inside this <DIV> can either be blank, or contain any other content which the AJAX code will then either replace or append/add to. In the example here, the existing code of the <DIV> is the first 14 results of a category list, and when you click the "Load More Results" button, this is appended to by the AJAX code as shown below.

Next is the JavaScript for the event listener / event handler (which loads the AJAX content). These are both done here in the one same JavaScript function. This is the actual .js file as used on this website:

// JavaScript Document
 (function($) {
		   
	// alert ('Yeah!');  // This when uncommented tests if this 
	// javascript file has been loaded and is running.
	
	// Uncomment to test if jQuery is loaded and is working
	//   $(document).ready(function($) {
	//   alert("JS and jquery are working");
	//   });
  
	// Name a variable for the button's ID. This was in the
	// original script, so I left it in here, though it
	// could be just as easily hardcoded
	var listingMoreButton = $('#listing-more-button');

	// Name a variable for the ID of the DIV that will get the
	// AJAX-loaded content. This (as above) could also just as 
	// easily be hardcoded into the line
	// 		$(listingMoreHTML).append(data);
	// Which would then look like 	
	//		$('#listing-more-html').append(data);
	var listingMoreHTML = $('#listing-more-html');

	// Set up an event listener for the listingMoreButton.
	$(listingMoreButton).click(function(e) 
	{
		// $(listingMoreHTML).load("listing-ajax.php"); 
		// This works but it replaces the entire DIV's contents 
		// with the new HTML -- we want to append (i.e. add)
		// to the existing contents, not replace them.
		
		// $(listingMoreHTML).append($('<div>').load('listing-ajax.php'));
		// This almost worked but it created a new <div> inside
		// the existing one, which conflicted with some of the CSS
		// formatting of the page.
		
		// The version below works as intended (to append to the DIV)
		
		$.ajax({
		  url: 'listing-ajax.php',
		  success: function(data) {
			$('.result').html(data);
			$(listingMoreHTML).append(data);
		  }
		});

	});
	
})(jQuery);

Nearly all of the above code is comments, there are only a few lines which do the actual work.

In the comments are some debugging commands (which I left in in case I want to re-use this for some other functionality later on and experiment with it, perhaps on a different website), and two other ways of loading the contents of the <DIV> with AJAX, which I didn't use (the reasons are explained in the commented code).

You can see the W3Schools page with the details of the jQuery ajax() method here.

Next is the inner "web page" which is loaded by AJAX into the <DIV>. This is a modified version of the actual one used on this website:

<?php 

require("file-to-initialise-sessions-and-database.php");

// Exit if this script wasn't called from the proper page
if (!isset($_SESSION['number_of_next_page'])) exit(); 

// Query the DB for the listing results
require('file-to-query-the-database-for-the-new-results.php'); 

// I should really have used a variable for the '14' but
// it was 2am and I was feeling tired. 
$_SESSION['number_of_next_page'] += 14;

while( $latestrow = $sql->fetchrow($result))
{
	require('file-to-show-one-result-item.php'); 
	$_SESSION['items_shown']++; 
}                                 

// Hide the "Show More" button when all the results are displayed.
if ($_SESSION['items_shown'] >= $_SESSION['total_returned']) 
{
	echo "<script>
      $('#listing-more-button').hide();
	</script>";
	//echo'sdffgsdfsdfsdfsdf'; // This was a debugging test
}                          

?>

The above "web page" could be anything you want to display inside the <DIV>. Here is is showing the next 14 results. And when all the results are finally shown, there is code at the end of the page to hide the button for "Load More Results".

There are session variables used to pass information between the main container page and the inner AJAX-loaded page which is appended inside the <DIV>. These are needed because the two pages (inner and outer) are independent at the server level (meaning that the web server and PHP sees the inner page as if loading a brand new page). This also means that you need to re-inisialise sessions (and your database connection, etc., if used) in the inner page, as if the browser was loading a complete new web page. And that ordinary PHP variables will have different scopes between the two pages (as if they were two completely separate web pages, which is how the server sees them as) — hence the need for session variables to pass any data you need between the inner and outer page at the server level.

However, the two pages (inner and outer) are joined/related at the client-side level. This means for e.g. that the inner "web page" doesn't need things like <HTML> or <BODY> tags. And also that the same DOM and JavaScript identifiers can be used to refer to elements in both pages in the client-side code (an example of this is seen in the above code at the end, where the #listing-more-button is referred to in the inner page, yet it refers to an id attribute which exists in the outer page).

Cover image by Shutterstock

Categories Javascript,Coding
Byte.Yoga Homepage - Australian Cyber Security Web Magazine

Share This Page

If you liked this page, please share it with others! You can use the links to share on Facebook, Twitter, LinkedIn, Pinterest, and Email. Ther is also an RSS feed to get updates for the website.