AJAX Examples

AJAX (Asynchronous JavaScript and XML) allows web applications to interact with the server asynchronously without reloading the entire page. Here are some common examples of how AJAX is used:

1. Load Data Without Reloading

  • Example: Fetching user profiles or posts in a social media app without refreshing the page.
  • Code:
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onload = function() {
    if (xhr.status === 200) {
        document.getElementById("content").innerHTML = xhr.responseText;
    }
};
xhr.send();
  • Real-world use: Loading a blog’s comment section dynamically.

2. Form Submission

  • Example: Submitting a form without reloading the page.
  • Code:
const form = document.querySelector("#myForm");
form.addEventListener("submit", function(event) {
    event.preventDefault();
    const formData = new FormData(form);
    fetch("/submit", {
        method: "POST",
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById("message").innerText = "Form submitted successfully!";
    });
});
  • Real-world use: Online contact forms or surveys.

3. Search Suggestions

  • Example: Providing search suggestions as users type.
  • Code:
document.getElementById("search").addEventListener("keyup", function() {
    const query = this.value;
    const xhr = new XMLHttpRequest();
    xhr.open("GET", `/search?q=${query}`, true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            const suggestions = JSON.parse(xhr.responseText);
            displaySuggestions(suggestions);
        }
    };
    xhr.send();
});

function displaySuggestions(suggestions) {
    const suggestionBox = document.getElementById("suggestions");
    suggestionBox.innerHTML = suggestions.map(s => `<li>${s}</li>`).join("");
}
  • Real-world use: Search bars on e-commerce websites.

4. Live Chat Applications

  • Example: Real-time messaging updates between users.
  • Code:
setInterval(() => {
    fetch("/getMessages")
    .then(response => response.json())
    .then(data => {
        const chatBox = document.getElementById("chatBox");
        chatBox.innerHTML = data.map(msg => `<p>${msg}</p>`).join("");
    });
}, 1000);
  • Real-world use: Support chat systems or messaging platforms.

5. Dynamic Content Updates

  • Example: Updating weather information or stock prices.
  • Code:
setInterval(() => {
    fetch("/getWeather")
    .then(response => response.json())
    .then(data => {
        document.getElementById("weather").innerText = `Temperature: ${data.temp}°C`;
    });
}, 60000);
  • Real-world use: Financial dashboards or weather widgets.

Benefits of AJAX Examples:

  • Improved User Experience: Reduces unnecessary page reloads.
  • Efficient Server Communication: Loads only necessary data.
  • Enhanced Responsiveness: Interacts with users in real-time.

Explore more tutorials on AJAX and related technologies at The Coding College.

Leave a Comment