Dynamic Content Load Using jQuery and AJAX in PHP

Dynamic Content Load Using jQuery and AJAX in PHP

Dynamic content loading for webpage is simple approach of loading page content by click on navigation menu link without page refresh. One of my blog readers requested me to write this tutorial. So, in this post we will discuss how to load dynamic content using jQuery and AJAX. Page content loads faster without refreshing it with jquery and JAX in PHP.
Dynamic Content Load Using jQuery and AJAX in PHP
In this post page title and contents are stored in database. Page title as navigation menu and home page content are loading here by default.

On click of menu link calling jQuery function getContent() for AJAX request and loading page content from database in load_content.php page. On success, response is loading in <div id=”content”></div>

Dynamic HTML Menu

Loading page title as navigation menu and displaying div for loading dynamic output by AJAX request.

<?php
require_once 'dbconfig.php';
$db = new database();
//get page id and title
$page_data = $db->query("SELECT `id`,`title` FROM `page`");
?>
<ul>
<?php if($page_data):
foreach($page_data as $data){  ?>
<li><button onClick="getContent(<?php echo $data['id']; ?>);" class="link"><?=$data['title']; ?></button></li>
<?php  }
endif; ?>
</ul>
<div id="content"></div>

jQuery

In this function passing page id using AJAX request on “load_content.php” page and retrieve content of matching id from database and load this content in output content div area after successful response.

<script>
function getContent(id){
$.ajax({
url: 'load_content.php',
cache: false,
type: 'POST',
data: {id:id},
success:function(response){
$("#content").html(response);
}
});
}
//default homepage content loading
getContent(1);
</script>

Retrieving Page content in PHP

Getting page content from database based on id passed using jQuery function getContent();

<?php
require_once 'dbconfig.php';
$db = new database;
//get page content by page id
$page_data = $db->query("SELECT `content` FROM `page` WHERE `id` = '".$_POST['id']."'");
if($page_data):
echo "<p>".$page_data[0]['content']."</p>"; 
endif;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *