How to load dynamic contents using jquery ajax?
Dynamic content loading
Loading a webpage with dynamic content is very easy by using jQuery and AJAX.
In this tutorial, we have stored page contents in 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 database. This content will be dynamically loaded to the output area on successful completion of the AJAX flow.
File name : index.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$pages = $db_handle->runQuery("SELECT * FROM pages");
?>
<html>
<head>
<title>Load Dynamic Content using jQuery AJAX</title>
<script src="http://code.jquery.com/jquery-2.1.1.js"></script>
<style type="text/css" media="screen">
body{width:610;}
#menu{background: #D8F9D3;height: 40px;border-top: #F0F0F0 2px solid;}
#menu input[type="button"]{margin-left: 2px;padding: 0px 15px;height: 40px;border: 0px;background: #F0F0F0;}
#output{min-height:300px;border:#F0F0F0 1px solid;padding:15px;}
</style>
<script type="text/javascript">
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);}
});
}
getPage(1);
</script>
</head>
<body>
<?php
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>
</body>
</html>
File name : dbcontroller.php
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "";
private $database = "phppot_examples";
function __construct() {
$conn = $this->connectDB();
if(!empty($conn)) {
$this->selectDB($conn);
}
}
function connectDB() {
$conn = mysql_connect($this->host,$this->user,$this->password);
return $conn;
}
function selectDB($conn) {
mysql_select_db($this->database,$conn);
}
function runQuery($query) {
$result = mysql_query($query);
while($row=mysql_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysql_query($query);
$rowcount = mysql_num_rows($result);
return $rowcount;
}
}
?>
File name : get_page.php
<?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 } ?>
Output :-
Previous
Next
Trending Tutorials
Download Live Projects
5
(0 )
4
(0 )
3
(0 )
2
(0 )
1
(0 )
Write Review Here
Review