AJAX Examples
Practical AJAX code examples for beginners
💡 AJAX Examples
Learn AJAX through practical, real-world examples. These simple code snippets demonstrate common AJAX patterns you'll use in everyday web development, from loading text to handling JSON data and managing errors effectively.
// Simple AJAX example
fetch('data.txt')
.then(response => response.text())
.then(data => console.log(data));
Example Categories
Load Text
Fetch plain text files
fetch('file.txt')
.then(r => r.text())
Load JSON
Fetch JSON data
fetch('data.json')
.then(r => r.json())
Load HTML
Fetch HTML content
fetch('page.html')
.then(r => r.text())
Load XML
Fetch XML documents
fetch('data.xml')
.then(r => r.text())
🔹 Example 1: Load Text File
The simplest AJAX example loads a text file and displays its content. This demonstrates the basic fetch API pattern: make a request, wait for the response, convert it to text, and then use the data.
<button onclick="loadText()">Load Text</button>
<div id="output"></div>
<script>
function loadText() {
fetch('sample.txt')
.then(response => response.text())
.then(data => {
document.getElementById('output').innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
Output:
Hello! This is content from sample.txt file.
🔹 Example 2: Load JSON Data
Fetch JSON data from a file or API and display it on your page. JSON is the most common data format for AJAX requests because it's easy to parse and work with in JavaScript applications.
<button onclick="loadJSON()">Load Users</button>
<div id="users"></div>
<script>
function loadJSON() {
fetch('users.json')
.then(response => response.json())
.then(data => {
let html = '';
data.forEach(user => {
html += `<p>${user.name} - ${user.email}</p>`;
});
document.getElementById('users').innerHTML = html;
});
}
</script>
Output:
John Doe - [email protected]
Jane Smith - [email protected]
🔹 Example 3: Load HTML Content
Load HTML fragments from external files and inject them into your page. This is useful for loading reusable components like headers, footers, or content sections without duplicating code across multiple pages.
<button onclick="loadHTML()">Load Content</button>
<div id="content"></div>
<script>
function loadHTML() {
fetch('content.html')
.then(response => response.text())
.then(html => {
document.getElementById('content').innerHTML = html;
});
}
</script>
<!-- content.html -->
<h2>Welcome!</h2>
<p>This content was loaded dynamically.</p>
Output:
Welcome!
This content was loaded dynamically.
🔹 Example 4: POST Request
Send data to the server using POST method. This is essential for submitting forms, creating new records, or sending user input to the server for processing without navigating away from the current page.
<button onclick="sendData()">Send Data</button>
<div id="response"></div>
<script>
function sendData() {
const data = {
name: 'John Doe',
email: '[email protected]'
};
fetch('submit.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
document.getElementById('response').innerHTML =
`<p>${result.message}</p>`;
});
}
</script>
Output:
✓ Data submitted successfully!
🔹 Example 5: Error Handling
Always handle errors in AJAX requests to provide better user experience. This example shows how to catch network errors, server errors, and display appropriate messages to users when something goes wrong.
function loadDataWithErrorHandling() {
fetch('data.json')
.then(response => {
if(!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
alert('Failed to load data. Please try again.');
});
}
Output (on error):
⚠ Failed to load data. Please try again.
🔹 Example 6: Loading Indicator
Show a loading spinner while waiting for AJAX requests to complete. This provides visual feedback to users, letting them know the application is working and preventing confusion during longer requests.
<button onclick="loadWithSpinner()">Load Data</button>
<div id="spinner" style="display:none;">Loading...</div>
<div id="result"></div>
<script>
function loadWithSpinner() {
const spinner = document.getElementById('spinner');
const result = document.getElementById('result');
spinner.style.display = 'block';
result.innerHTML = '';
fetch('data.json')
.then(response => response.json())
.then(data => {
spinner.style.display = 'none';
result.innerHTML = `<p>Data loaded: ${data.length} items</p>`;
});
}
</script>
Output:
Data loaded: 25 items