AJAX Applications

Building dynamic web applications with AJAX

πŸš€ What are AJAX Applications?

AJAX applications are interactive web apps that update content dynamically without full page reloads. They provide smooth, desktop-like experiences by exchanging small amounts of data with servers in the background.


// Basic AJAX application structure
function loadContent(url) {
  fetch(url)
    .then(response => response.text())
    .then(data => updatePage(data));
}
                                    

Common AJAX Applications

πŸ“§

Email Clients

Gmail-style web email

loadEmails()
sendEmail()
deleteEmail()
πŸ’¬

Chat Apps

Real-time messaging

sendMessage()
receiveMessages()
updateStatus()
πŸ—ΊοΈ

Maps

Interactive map applications

loadMapTiles()
searchLocation()
getDirections()
πŸ›’

Shopping Carts

Dynamic e-commerce

addToCart()
updateQuantity()
checkout()

πŸ”Ή Single Page Application (SPA)

SPAs load a single HTML page and dynamically update content as users interact. This approach eliminates page refreshes, providing faster navigation and a more fluid user experience similar to native desktop applications.

// Simple SPA router
function navigate(page) {
  fetch(`pages/${page}.html`)
    .then(response => response.text())
    .then(html => {
      document.getElementById('content').innerHTML = html;
      history.pushState(null, '', `/${page}`);
    });
}

// Usage
navigate('home');
navigate('about');
navigate('contact');

Output:

βœ“ Page loaded without refresh

βœ“ URL updated: /about

πŸ”Ή Auto-Complete Search

Auto-complete provides search suggestions as users type, improving usability and helping users find content faster. The application sends partial queries to the server and displays matching results in real-time below the input field.

<!-- Auto-complete search -->
<input type="text" id="searchBox" placeholder="Search...">
<ul id="suggestions"></ul>

<script>
const searchBox = document.getElementById('searchBox');
const suggestions = document.getElementById('suggestions');

searchBox.addEventListener('input', function() {
  const query = this.value;
  
  if(query.length < 2) {
    suggestions.innerHTML = '';
    return;
  }
  
  fetch(`autocomplete.php?q=${query}`)
    .then(response => response.json())
    .then(data => {
      suggestions.innerHTML = data
        .map(item => `<li>${item}</li>`)
        .join('');
    });
});
</script>

Output:

Suggestions:

  • JavaScript Tutorial
  • Java Programming
  • jQuery Basics

πŸ”Ή Live Form Validation

Validate form inputs instantly as users type, providing immediate feedback without waiting for form submission. This improves user experience by catching errors early and reducing frustration from failed submissions after completing long forms.

<!-- Live username validation -->
<input type="text" id="username" placeholder="Choose username">
<span id="usernameStatus"></span>

<script>
document.getElementById('username').addEventListener('blur', function() {
  const username = this.value;
  const status = document.getElementById('usernameStatus');
  
  fetch(`check-username.php?username=${username}`)
    .then(response => response.json())
    .then(data => {
      if(data.available) {
        status.textContent = 'βœ“ Available';
        status.style.color = 'green';
      } else {
        status.textContent = 'βœ— Already taken';
        status.style.color = 'red';
      }
    });
});
</script>

Output:

βœ“ Available

πŸ”Ή Infinite Scroll

Load more content automatically as users scroll down the page, eliminating pagination buttons. This technique is popular in social media feeds and image galleries, providing seamless browsing without interrupting the user's flow.

// Infinite scroll implementation
let page = 1;
let loading = false;

window.addEventListener('scroll', function() {
  if(loading) return;
  
  const scrollPosition = window.innerHeight + window.scrollY;
  const pageHeight = document.body.offsetHeight;
  
  if(scrollPosition >= pageHeight - 100) {
    loading = true;
    page++;
    
    fetch(`load-posts.php?page=${page}`)
      .then(response => response.json())
      .then(posts => {
        posts.forEach(post => {
          document.getElementById('feed').innerHTML += 
            `<div class="post">${post.content}</div>`;
        });
        loading = false;
      });
  }
});

πŸ”Ή Real-Time Notifications

Display instant notifications to users without page refresh, keeping them informed of new messages, updates, or alerts. The application periodically checks the server for new notifications and displays them in a non-intrusive way.

// Check for new notifications
function checkNotifications() {
  fetch('get-notifications.php')
    .then(response => response.json())
    .then(notifications => {
      if(notifications.length > 0) {
        showNotification(notifications[0].message);
      }
    });
}

// Check every 30 seconds
setInterval(checkNotifications, 30000);

Output:

πŸ”” You have 3 new messages

🧠 Test Your Knowledge

What does SPA stand for in web development?