Dynamic Content Loading

Rumman Ansari   Software Engineer   0000-00-00 00:00:00   564  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

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 loadDynamicContent JavaScript function.
  • The function makes an AJAX request to the content.php file.
  • 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.



Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.