Table of Contents
Dynamic Content Loading
Example 1: Dynamic Content Loading
Objective: Load dynamic content without refreshing the entire page.
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Content Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="dynamic-content-container">
<!-- Content will be loaded here -->
</div>
<button onclick="loadDynamicContent()">Load Content</button>
</body>
</html>
PHP (content.php):
<?php
// content.php - Simulating dynamic content generation
echo "Dynamic content loaded at: " . date("h:i:s");
?>
JavaScript (script.js):
function loadDynamicContent() {
// Using jQuery for AJAX request
$.ajax({
url: 'content.php',
type: 'GET',
success: function(response) {
// Update the content container with the retrieved data
$('#dynamic-content-container').html(response);
},
error: function(error) {
console.log('Error:', error);
}
});
}
Explanation:
- Clicking the "Load Content" button triggers the
loadDynamicContentJavaScript function. - The function makes an AJAX request to the
content.phpfile. - The PHP file generates dynamic content (in this case, a timestamp).
- The JavaScript function updates the content container with the received data without refreshing the entire page.
This example demonstrates how PHP can dynamically generate content, and AJAX helps in updating specific parts of the page asynchronously.