AJAX Examples
Practical AJAX code examples and demos
💡 AJAX Examples
Learn AJAX through practical, working examples! Each example includes complete code that you can copy and use in your own projects.
// Quick AJAX example
fetch('/api/data')
.then(response => response.json())
.then(data => {
document.getElementById('result').innerHTML = data.message;
});
Example Categories
Basic Examples
Simple AJAX requests
fetch('/api/hello')
Form Examples
Submit forms with AJAX
new FormData(form)
Dynamic Content
Update page content
element.innerHTML = data
Advanced Examples
Complex AJAX applications
Promise.all(requests)
🔹 Example 1: Load Text Content
The simplest AJAX example - load text from a file:
🔸 HTML
<button onclick="loadText()">Load Text</button>
<div id="text-content">Click button to load content</div>
🔸 JavaScript
function loadText() {
fetch('sample.txt')
.then(response => response.text())
.then(text => {
document.getElementById('text-content').innerHTML = text;
})
.catch(error => {
document.getElementById('text-content').innerHTML = 'Error loading content';
console.error('Error:', error);
});
}
🔸 sample.txt
Hello! This content was loaded using AJAX.
No page refresh needed! 🎉
Try it:
🔹 Example 2: Weather App
Fetch weather data from an API:
🔸 HTML
<div class="weather-app">
<input type="text" id="city-input" placeholder="Enter city name">
<button onclick="getWeather()">Get Weather</button>
<div id="weather-result"></div>
</div>
🔸 JavaScript
function getWeather() {
const city = document.getElementById('city-input').value;
const resultDiv = document.getElementById('weather-result');
if (!city) {
resultDiv.innerHTML = 'Please enter a city name';
return;
}
resultDiv.innerHTML = 'Loading weather data...';
// Using OpenWeatherMap API (you need an API key)
const apiKey = 'YOUR_API_KEY';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('City not found');
}
return response.json();
})
.then(data => {
displayWeather(data);
})
.catch(error => {
resultDiv.innerHTML = `Error: ${error.message}`;
});
}
function displayWeather(data) {
const resultDiv = document.getElementById('weather-result');
const html = `
<div class="weather-card">
<h3>${data.name}, ${data.sys.country}</h3>
<div class="temperature">${Math.round(data.main.temp)}°C</div>
<div class="description">${data.weather[0].description}</div>
<div class="details">
<p>Feels like: ${Math.round(data.main.feels_like)}°C</p>
<p>Humidity: ${data.main.humidity}%</p>
<p>Wind: ${data.wind.speed} m/s</p>
</div>
</div>
`;
resultDiv.innerHTML = html;
}
Demo Result:
London, GB
Feels like: 13°C
Humidity: 65%
Wind: 3.2 m/s
🔹 Example 3: Todo List App
Complete todo application with AJAX:
🔸 HTML
<div class="todo-app">
<h2>My Todo List</h2>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="Add new todo..." required>
<button type="submit">Add Todo</button>
</form>
<div id="todo-list"></div>
</div>
🔸 JavaScript
let todos = [];
// Load todos when page loads
document.addEventListener('DOMContentLoaded', loadTodos);
// Handle form submission
document.getElementById('todo-form').addEventListener('submit', function(e) {
e.preventDefault();
addTodo();
});
function loadTodos() {
fetch('/api/todos.php')
.then(response => response.json())
.then(data => {
todos = data;
displayTodos();
})
.catch(error => {
console.error('Error loading todos:', error);
});
}
function addTodo() {
const input = document.getElementById('todo-input');
const text = input.value.trim();
if (!text) return;
const newTodo = {
text: text,
completed: false
};
fetch('/api/todos.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newTodo)
})
.then(response => response.json())
.then(data => {
if (data.success) {
newTodo.id = data.id;
todos.push(newTodo);
displayTodos();
input.value = '';
}
})
.catch(error => {
console.error('Error adding todo:', error);
});
}
function toggleTodo(id) {
const todo = todos.find(t => t.id === id);
if (!todo) return;
todo.completed = !todo.completed;
fetch(`/api/todos.php?id=${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ completed: todo.completed })
})
.then(response => response.json())
.then(data => {
if (data.success) {
displayTodos();
}
});
}
function deleteTodo(id) {
fetch(`/api/todos.php?id=${id}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
if (data.success) {
todos = todos.filter(t => t.id !== id);
displayTodos();
}
});
}
function displayTodos() {
const todoList = document.getElementById('todo-list');
if (todos.length === 0) {
todoList.innerHTML = '<p>No todos yet. Add one above!</p>';
return;
}
let html = '';
todos.forEach(todo => {
html += `
<div class="todo-item ${todo.completed ? 'completed' : ''}">
<input type="checkbox" ${todo.completed ? 'checked' : ''}
onchange="toggleTodo(${todo.id})">
<span class="todo-text">${todo.text}</span>
<button onclick="deleteTodo(${todo.id})" class="delete-btn">Delete</button>
</div>
`;
});
todoList.innerHTML = html;
}
🔸 CSS
.todo-app {
max-width: 500px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
.todo-item {
display: flex;
align-items: center;
padding: 10px;
border-bottom: 1px solid #eee;
}
.todo-item.completed .todo-text {
text-decoration: line-through;
color: #888;
}
.todo-text {
flex: 1;
margin: 0 10px;
}
.delete-btn {
background: #ff4444;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
}
🔹 Example 4: File Upload with Progress
Upload files with a progress bar:
🔸 HTML
<div class="upload-container">
<input type="file" id="file-input" multiple>
<button onclick="uploadFiles()">Upload Files</button>
<div id="upload-progress" style="display: none;">
<div class="progress-bar">
<div id="progress-fill" class="progress-fill"></div>
</div>
<div id="progress-text">0%</div>
</div>
<div id="upload-result"></div>
</div>
🔸 JavaScript
function uploadFiles() {
const fileInput = document.getElementById('file-input');
const files = fileInput.files;
if (files.length === 0) {
alert('Please select files to upload');
return;
}
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('files[]', files[i]);
}
const progressContainer = document.getElementById('upload-progress');
const progressFill = document.getElementById('progress-fill');
const progressText = document.getElementById('progress-text');
const resultDiv = document.getElementById('upload-result');
// Show progress bar
progressContainer.style.display = 'block';
resultDiv.innerHTML = '';
// Create XMLHttpRequest for progress tracking
const xhr = new XMLHttpRequest();
// Track upload progress
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
progressFill.style.width = percentComplete + '%';
progressText.textContent = Math.round(percentComplete) + '%';
}
});
// Handle completion
xhr.addEventListener('load', function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
if (response.success) {
resultDiv.innerHTML = '<p style="color: green;">✅ Files uploaded successfully!</p>';
} else {
resultDiv.innerHTML = '<p style="color: red;">❌ Upload failed: ' + response.message + '</p>';
}
} else {
resultDiv.innerHTML = '<p style="color: red;">❌ Upload failed</p>';
}
// Hide progress bar after a delay
setTimeout(() => {
progressContainer.style.display = 'none';
progressFill.style.width = '0%';
progressText.textContent = '0%';
}, 2000);
});
// Handle errors
xhr.addEventListener('error', function() {
resultDiv.innerHTML = '<p style="color: red;">❌ Upload error occurred</p>';
progressContainer.style.display = 'none';
});
// Send the request
xhr.open('POST', '/api/upload.php');
xhr.send(formData);
}
🔸 CSS for Progress Bar
.progress-bar {
width: 100%;
height: 20px;
background-color: #f0f0f0;
border-radius: 10px;
overflow: hidden;
margin: 10px 0;
}
.progress-fill {
height: 100%;
background-color: #4CAF50;
width: 0%;
transition: width 0.3s ease;
}