Dynamic Content Load using jQuery AJAX

Loading a web page with dynamic content is very easy by using jQuery and AJAX. We have already seen about how to load content dynamically on page scroll in a previous jQuery tutorial.

In this tutorial, we have stored page contents in the database. We are displaying page titles as header menu on top the content area. On clicking menu, we will call a jQuery function to send an AJAX request to get page content from the database. This content will be dynamically loaded to the output area on successful completion of the AJAX flow.

jquery-ajax-dynamic-load

View DemoDownload

HTML Menu Navigation

This code is for creating HTML for displaying menu navigation and output area to load dynamic content from AJAX. We are getting page titles from the database to show the menu.

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$pages = $db_handle->runQuery("SELECT * FROM pages");
if(!empty($pages)) {
?>
<div id="menu">
<?php 
foreach($pages as $page) { 
?>
<input type="button" value="<?php echo $page["title"]; ?>" onClick="getPage(<?php echo $page["id"]; ?>);" />
<?php } ?>	
</div>
<?php } ?>	
<div id="output"></div>

jQuery AJAX Dynamic Content Loading

This jQuery function receives page id and sends it to PHP a page via an AJAX request. With the reference of this id, the page information will be received and loaded into the response area.

function getPage(id) {
	$('#output').html('<img src="LoaderIcon.gif" />');
	jQuery.ajax({
		url: "get_page.php",
		data:'id='+id,
		type: "POST",
		success:function(data){$('#output').html(data);}
	});
}

Getting Page Content in PHP

This code fetches page content based on the id passed via jQuery AJAX data-string.

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$pages = $db_handle->runQuery("SELECT * FROM pages WHERE id = ".$_REQUEST['id']);
if(!empty($pages)) {
?>
<h3><?php echo $pages[0]['title'];?></h3>
<div><?php echo $pages[0]['content'];?></p>
<?php } ?>

View DemoDownload

This jQuery code tutorial was published on November 26, 2014.

↑ Back to Top