AJAX Examples

Welcome to The Coding College, where you can learn cutting-edge programming techniques! In this tutorial, we’ll explore practical AJAX examples to help you understand how it enhances web development. AJAX allows asynchronous communication between a web browser and a server, enabling dynamic updates without reloading the page.

Why Use AJAX?

  • Improve User Experience: Update page content dynamically without refreshing.
  • Save Bandwidth: Only the required data is exchanged between the browser and server.
  • Faster Performance: Reduces the time spent loading a page.

Let’s look at some practical AJAX examples and how they can be implemented.

Example 1: Simple Data Fetch

This example demonstrates fetching text from the server and displaying it on a webpage.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Example - Simple Fetch</title>
</head>
<body>
    <h1>AJAX Simple Fetch Example</h1>
    <button id="fetchButton">Fetch Data</button>
    <p id="result"></p>

    <script>
        document.getElementById("fetchButton").addEventListener("click", function () {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", "data.txt", true); // Fetches a plain text file named "data.txt"
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("result").innerText = xhr.responseText;
                }
            };
            xhr.send();
        });
    </script>
</body>
</html>

Server-side File (data.txt):

Hello! This is data fetched via AJAX.

Example 2: Fetch JSON Data

Here’s how you can fetch and display data in JSON format using AJAX.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Example - JSON Fetch</title>
</head>
<body>
    <h1>AJAX JSON Example</h1>
    <button id="fetchJson">Fetch User Data</button>
    <div id="output"></div>

    <script>
        document.getElementById("fetchJson").addEventListener("click", function () {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", "data.json", true); // Fetch JSON file
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const users = JSON.parse(xhr.responseText);
                    let output = "<h2>Users:</h2><ul>";
                    users.forEach(user => {
                        output += `<li>${user.name} - ${user.email}</li>`;
                    });
                    output += "</ul>";
                    document.getElementById("output").innerHTML = output;
                }
            };
            xhr.send();
        });
    </script>
</body>
</html>

Server-side File (data.json):

[
    { "name": "John Doe", "email": "[email protected]" },
    { "name": "Jane Smith", "email": "[email protected]" },
    { "name": "Mike Johnson", "email": "[email protected]" }
]

Example 3: Submit Form Data via AJAX

This example demonstrates sending form data to a server using AJAX.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Example - Form Submission</title>
</head>
<body>
    <h1>Submit Form Data with AJAX</h1>
    <form id="userForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br><br>
        <button type="submit">Submit</button>
    </form>
    <div id="response"></div>

    <script>
        document.getElementById("userForm").addEventListener("submit", function (e) {
            e.preventDefault(); // Prevent default form submission

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "submit.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            // Collect form data
            const name = document.getElementById("name").value;
            const email = document.getElementById("email").value;
            const params = `name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}`;

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("response").innerText = xhr.responseText;
                }
            };
            xhr.send(params);
        });
    </script>
</body>
</html>

Server-side PHP File (submit.php):

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    echo "User: $name, Email: $email has been submitted successfully!";
}
?>

Example 4: Real-Time Search

This example implements a real-time search feature using AJAX.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Example - Live Search</title>
</head>
<body>
    <h1>Real-Time Search</h1>
    <input type="text" id="searchBox" placeholder="Search users...">
    <ul id="searchResults"></ul>

    <script>
        document.getElementById("searchBox").addEventListener("input", function () {
            const query = this.value;
            const xhr = new XMLHttpRequest();
            xhr.open("GET", `search.php?q=${encodeURIComponent(query)}`, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("searchResults").innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        });
    </script>
</body>
</html>

Server-side PHP File (search.php):

<?php
$users = ["John Doe", "Jane Smith", "Mike Johnson", "Emily Davis", "Paul Brown"];
$q = $_GET["q"];
$results = array_filter($users, function($user) use ($q) {
    return stripos($user, $q) !== false;
});

foreach ($results as $result) {
    echo "<li>$result</li>";
}
?>

Conclusion

AJAX is a powerful tool for building dynamic and responsive web applications. These examples showcase the most common use cases, from fetching data to submitting forms and implementing live search.

Leave a Comment