AJAX Applications
Real-world AJAX application examples
🚀 Real AJAX Applications
Discover how AJAX powers modern web applications! From live chat to auto-complete, AJAX makes websites interactive and user-friendly.
// Real-time notifications
setInterval(() => {
fetch('/api/notifications')
.then(response => response.json())
.then(notifications => updateNotifications(notifications));
}, 5000);
Popular AJAX Applications
Live Chat
Real-time messaging systems
WhatsApp Web
Slack
Discord
Auto-Complete
Search suggestions as you type
Google Search
Amazon
YouTube
Dashboards
Real-time data visualization
Analytics
Monitoring
Trading
E-Commerce
Shopping cart and checkout
Add to Cart
Wishlist
Reviews
🔹 Live Search Application
Build a search that shows results as you type:
🔸 HTML Structure
<div class="search-container">
<input type="text" id="search-input" placeholder="Search products..." autocomplete="off">
<div id="search-results" class="search-results"></div>
</div>
<style>
.search-container {
position: relative;
width: 300px;
margin: 20px auto;
}
.search-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: white;
border: 1px solid #ddd;
border-top: none;
max-height: 200px;
overflow-y: auto;
display: none;
}
.search-result-item {
padding: 10px;
cursor: pointer;
border-bottom: 1px solid #eee;
}
.search-result-item:hover {
background-color: #f5f5f5;
}
</style>
🔸 JavaScript Implementation
let searchTimeout;
const searchInput = document.getElementById('search-input');
const searchResults = document.getElementById('search-results');
searchInput.addEventListener('input', function() {
const query = this.value.trim();
// Clear previous timeout
clearTimeout(searchTimeout);
if (query.length < 2) {
hideResults();
return;
}
// Debounce search - wait 300ms after user stops typing
searchTimeout = setTimeout(() => {
performSearch(query);
}, 300);
});
function performSearch(query) {
// Show loading indicator
searchResults.innerHTML = '<div class="search-result-item">Searching...</div>';
searchResults.style.display = 'block';
fetch(`/api/search.php?q=${encodeURIComponent(query)}`)
.then(response => response.json())
.then(results => {
displayResults(results);
})
.catch(error => {
searchResults.innerHTML = '<div class="search-result-item">Error occurred</div>';
});
}
function displayResults(results) {
if (results.length === 0) {
searchResults.innerHTML = '<div class="search-result-item">No results found</div>';
return;
}
let html = '';
results.forEach(item => {
html += `<div class="search-result-item" onclick="selectItem('${item.id}')">
<strong>${item.name}</strong>
<br><small>${item.description}</small>
</div>`;
});
searchResults.innerHTML = html;
}
function selectItem(itemId) {
// Handle item selection
console.log('Selected item:', itemId);
hideResults();
}
function hideResults() {
searchResults.style.display = 'none';
}
// Hide results when clicking outside
document.addEventListener('click', function(e) {
if (!e.target.closest('.search-container')) {
hideResults();
}
});
🔹 Real-Time Notifications
Create a notification system that updates automatically:
🔸 Notification HTML
<div class="notification-bell" onclick="toggleNotifications()">
🔔 <span id="notification-count" class="notification-count">0</span>
</div>
<div id="notification-panel" class="notification-panel">
<h3>Notifications</h3>
<div id="notification-list">
<p>No new notifications</p>
</div>
</div>
<style>
.notification-bell {
position: relative;
cursor: pointer;
font-size: 24px;
display: inline-block;
}
.notification-count {
position: absolute;
top: -8px;
right: -8px;
background: red;
color: white;
border-radius: 50%;
width: 20px;
height: 20px;
font-size: 12px;
display: flex;
align-items: center;
justify-content: center;
}
.notification-panel {
position: absolute;
top: 50px;
right: 20px;
width: 300px;
background: white;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
display: none;
z-index: 1000;
}
.notification-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
.notification-item.unread {
background-color: #f0f8ff;
}
</style>
🔸 Real-Time Updates
let notificationPanel = document.getElementById('notification-panel');
let notificationCount = document.getElementById('notification-count');
let notificationList = document.getElementById('notification-list');
// Check for new notifications every 10 seconds
setInterval(checkNotifications, 10000);
function checkNotifications() {
fetch('/api/notifications.php')
.then(response => response.json())
.then(data => {
updateNotifications(data.notifications);
updateNotificationCount(data.unread_count);
})
.catch(error => console.error('Error:', error));
}
function updateNotifications(notifications) {
if (notifications.length === 0) {
notificationList.innerHTML = '<p>No new notifications</p>';
return;
}
let html = '';
notifications.forEach(notification => {
html += `<div class="notification-item ${notification.read ? '' : 'unread'}">
<strong>${notification.title}</strong>
<p>${notification.message}</p>
<small>${notification.time}</small>
</div>`;
});
notificationList.innerHTML = html;
}
function updateNotificationCount(count) {
notificationCount.textContent = count;
notificationCount.style.display = count > 0 ? 'flex' : 'none';
}
function toggleNotifications() {
notificationPanel.style.display =
notificationPanel.style.display === 'block' ? 'none' : 'block';
}
// Initial load
checkNotifications();
🔹 Shopping Cart Application
Build an interactive shopping cart with AJAX:
🔸 Product Display
<div class="product-grid">
<div class="product-card">
<img src="product1.jpg" alt="Product 1">
<h3>Awesome Product</h3>
<p class="price">$29.99</p>
<button onclick="addToCart(1, 'Awesome Product', 29.99)">Add to Cart</button>
</div>
</div>
<div class="cart-summary">
<h3>Shopping Cart (<span id="cart-count">0</span>)</h3>
<div id="cart-items"></div>
<div class="cart-total">
Total: $<span id="cart-total">0.00</span>
</div>
</div>
🔸 Cart Functions
let cart = [];
function addToCart(productId, productName, price) {
// Check if item already in cart
const existingItem = cart.find(item => item.id === productId);
if (existingItem) {
existingItem.quantity += 1;
} else {
cart.push({
id: productId,
name: productName,
price: price,
quantity: 1
});
}
// Send to server
fetch('/api/cart.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'add',
product_id: productId,
quantity: 1
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
updateCartDisplay();
showMessage('Item added to cart!');
}
});
}
function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
fetch('/api/cart.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'remove',
product_id: productId
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
updateCartDisplay();
showMessage('Item removed from cart!');
}
});
}
function updateCartDisplay() {
const cartCount = document.getElementById('cart-count');
const cartItems = document.getElementById('cart-items');
const cartTotal = document.getElementById('cart-total');
// Update count
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
cartCount.textContent = totalItems;
// Update items
if (cart.length === 0) {
cartItems.innerHTML = '<p>Your cart is empty</p>';
} else {
let html = '';
cart.forEach(item => {
html += `<div class="cart-item">
<span>${item.name} x${item.quantity}</span>
<span>$${(item.price * item.quantity).toFixed(2)}</span>
<button onclick="removeFromCart(${item.id})">Remove</button>
</div>`;
});
cartItems.innerHTML = html;
}
// Update total
const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
cartTotal.textContent = total.toFixed(2);
}
function showMessage(message) {
// Simple message display
const messageDiv = document.createElement('div');
messageDiv.textContent = message;
messageDiv.style.cssText = 'position:fixed;top:20px;right:20px;background:green;color:white;padding:10px;border-radius:4px;z-index:1000;';
document.body.appendChild(messageDiv);
setTimeout(() => {
document.body.removeChild(messageDiv);
}, 3000);
}