PHP & AJAX Dynamic Content Examples

Explore practical examples of using PHP and AJAX to create dynamic web content that enhances user experience.
By Jamie

Introduction

Using PHP with AJAX allows developers to create dynamic content on web pages without requiring a full page reload. This approach enhances user experience by providing seamless interactivity and faster data retrieval. Below are three diverse examples showcasing how to implement PHP with AJAX for dynamic content.

Context

This example demonstrates a user search feature that retrieves results from a database as the user types in a search box. This functionality improves user experience by displaying results in real-time.

Example Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-Time User Search</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#search').on('keyup', function() {
                var query = $(this).val();
                $.ajax({
                    url: 'search.php',
                    method: 'POST',
                    data: { query: query },
                    success: function(data) {
                        $('#result').html(data);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <input type="text" id="search" placeholder="Search users...">
    <div id="result"></div>
</body>
</html>

search.php:

<?php
if (isset($_POST['query'])) {
    $conn = new mysqli('localhost', 'username', 'password', 'database');
    \(query = mysqli_real_escape_string(\)conn, $_POST['query']);
    \(sql = "SELECT * FROM users WHERE name LIKE '%\)query%'";
    \(result = \)conn->query($sql);
    if ($result->num_rows > 0) {
        while (\(row = \)result->fetch_assoc()) {
            echo '<p>' . $row['name'] . '</p>'; 
        }
    } else {
        echo 'No results found';
    }
    $conn->close();
}
?>

Notes

  • Ensure that you replace database connection parameters with your actual database credentials.
  • You can enhance the search feature by adding more fields to the SQL query.

Example 2: Live Chat System

Context

In this example, we will create a simple live chat system where users can send messages without refreshing the page. This is particularly useful for customer support applications.

Example Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Chat</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function loadChat() {
            $.ajax({
                url: 'chat.php',
                method: 'GET',
                success: function(data) {
                    $('#chat-box').html(data);
                }
            });
        }

        $(document).ready(function() {
            loadChat();
            setInterval(loadChat, 3000);

            $('#send-message').on('click', function() {
                var message = $('#message').val();
                $.ajax({
                    url: 'send.php',
                    method: 'POST',
                    data: { message: message },
                    success: function() {
                        $('#message').val('');
                        loadChat();
                    }
                });
            });
        });
    </script>
</head>
<body>
    <div id="chat-box"></div>
    <input type="text" id="message" placeholder="Type your message...">
    <button id="send-message">Send</button>
</body>
</html>

chat.php:

<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
$sql = "SELECT * FROM chat ORDER BY id ASC";
\(result = \)conn->query($sql);
if ($result->num_rows > 0) {
    while (\(row = \)result->fetch_assoc()) {
        echo '<p>' . $row['message'] . '</p>'; 
    }
}
$conn->close();
?>

send.php:

<?php
if (isset($_POST['message'])) {
    $conn = new mysqli('localhost', 'username', 'password', 'database');
    \(message = mysqli_real_escape_string(\)conn, $_POST['message']);
    \(sql = "INSERT INTO chat (message) VALUES ('\)message')";
    \(conn->query(\)sql);
    $conn->close();
}
?>

Notes

  • Replace the database connection parameters with your own.
  • For a more robust chat system, consider adding user authentication and timestamps.

Example 3: Dynamic Form Submission

Context

This example illustrates how to submit a form dynamically using AJAX, allowing for validation and submission without page reload. This can be useful for user registration or feedback forms.

Example Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Form Submission</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#myForm').on('submit', function(e) {
                e.preventDefault();
                $.ajax({
                    url: 'submit.php',
                    method: 'POST',
                    data: $(this).serialize(),
                    success: function(response) {
                        $('#response').html(response);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="myForm">
        <input type="text" name="username" placeholder="Username" required>
        <input type="email" name="email" placeholder="Email" required>
        <button type="submit">Submit</button>
    </form>
    <div id="response"></div>
</body>
</html>

submit.php:

<?php
if (isset(\(_POST['username']) && isset(\)_POST['email'])) {
    $conn = new mysqli('localhost', 'username', 'password', 'database');
    \(username = mysqli_real_escape_string(\)conn, $_POST['username']);
    \(email = mysqli_real_escape_string(\)conn, $_POST['email']);
    \(sql = "INSERT INTO users (username, email) VALUES ('\)username', '$email')";
    if (\(conn->query(\)sql) === TRUE) {
        echo 'Registration successful!';
    } else {
        echo 'Error: ' . $conn->error;
    }
    $conn->close();
}
?>

Notes

  • Ensure to validate user input to prevent SQL injection and other vulnerabilities.
  • You can expand this form by adding more fields and validation rules.