Master asynchronous JavaScript and XML (AJAX) with this comprehensive guide covering everything from classic implementations to modern approaches.
Quick Reference: Implementation Methods
Choose your AJAX implementation:
Method | Browser Support | Use Case | Modern Status |
---|---|---|---|
Fetch API | Modern browsers | Modern web apps | Recommended ✅ |
XMLHttpRequest | All browsers | Legacy support | Traditional approach |
jQuery AJAX | With jQuery | jQuery projects | Still widely used |
Axios | With library | Complex requests | Popular alternative |
XMLHttpRequest Essentials
Classic AJAX implementation:
// Basic GET request
const xhr = new XMLHttpRequest();
xhr.open('GET', 'api/data', true);
xhr.send();
Event | Handler | Purpose |
---|---|---|
onreadystatechange | xhr.onreadystatechange = function(){} | Track request states |
onload | xhr.onload = function(){} | Success handling |
onerror | xhr.onerror = function(){} | Error handling |
onprogress | xhr.onprogress = function(){} | Track progress |
Ready States Explained
Understanding XMLHttpRequest states:
State | Value | Meaning | Next Step |
---|---|---|---|
UNSENT | 0 | Initial state | Call open() |
OPENED | 1 | open() called | Call send() |
HEADERS_RECEIVED | 2 | Headers received | Wait for body |
LOADING | 3 | Loading body | Wait for completion |
DONE | 4 | Request complete | Process response |
Modern Fetch API Patterns
Contemporary AJAX with Fetch:
Operation | Code Example | Usage |
---|---|---|
GET Request | fetch(url).then(res => res.json()) | Retrieve data |
POST Request | fetch(url, {method: 'POST', body: data}) | Send data |
With Headers | fetch(url, {headers: {'Content-Type': 'application/json'}}) | Custom headers |
File Upload | fetch(url, {method: 'POST', body: formData}) | Upload files |
Request Configuration
Common request settings:
Property | Values | Purpose |
---|---|---|
method | GET, POST, PUT, DELETE | HTTP method |
headers | Object with headers | Request headers |
body | String, FormData, Blob | Request payload |
mode | cors, no-cors, same-origin | CORS settings |
credentials | include, same-origin, omit | Cookie handling |
Response Handling Methods
Process different response types:
Method | Usage | Returns |
---|---|---|
.json() | response.json() | Parsed JSON |
.text() | response.text() | Plain text |
.blob() | response.blob() | Binary data |
.formData() | response.formData() | Form data |
.arrayBuffer() | response.arrayBuffer() | Binary buffer |
jQuery AJAX Patterns
jQuery’s AJAX implementation:
$.ajax({
url: 'api/endpoint',
method: 'POST',
data: {key: 'value'}
})
Method | Syntax | Purpose |
---|---|---|
$.ajax() | $.ajax(url [, settings]) | Full configuration |
$.get() | $.get(url [, data] [, success]) | GET shorthand |
$.post() | $.post(url [, data] [, success]) | POST shorthand |
$.getJSON() | $.getJSON(url [, data] [, success]) | Get JSON data |
Axios Common Patterns
Modern AJAX with Axios:
Operation | Example | Description |
---|---|---|
GET | axios.get(url) | Simple GET |
POST | axios.post(url, data) | Send data |
Multiple | axios.all([req1, req2]) | Parallel requests |
Instance | axios.create({baseURL: 'api'}) | Custom config |
Error Handling Strategies
Handle AJAX errors effectively:
Scenario | Implementation | Purpose |
---|---|---|
Network Error | try/catch with async/await | Catch connection issues |
HTTP Error | Check response.ok or status | Handle HTTP errors |
Timeout | Set request timeout | Handle slow responses |
Validation | Check response data | Validate server response |
Security Best Practices
Keep your AJAX requests secure:
Practice | Implementation | Purpose |
---|---|---|
CSRF Token | Include in headers | Prevent CSRF attacks |
Input Validation | Validate before send | Prevent injection |
CORS Headers | Proper configuration | Control access |
Error Messages | Generic messages | Prevent info leak |
Performance Optimization
Optimize AJAX performance:
Technique | Method | Benefit |
---|---|---|
Caching | Cache-Control headers | Reduce server load |
Debouncing | Delay rapid requests | Prevent overload |
Compression | gzip/deflate | Reduce data size |
Connection Pooling | Keep-Alive | Reuse connections |
Debugging Tools
Essential debugging approaches:
Tool | Purpose | Usage |
---|---|---|
Network Panel | Monitor requests | Browser DevTools |
Console.log | Log responses | Basic debugging |
Postman | Test API calls | API development |
Charles Proxy | Detailed analysis | Deep inspection |
Common Use Cases
Real-world AJAX patterns:
Scenario | Implementation | Notes |
---|---|---|
Form Submit | Prevent default, collect data, send | User input handling |
Infinite Scroll | Load on scroll event | Pagination handling |
Auto-save | Debounced requests | Periodic updates |
File Upload | FormData with progress | Binary data handling |