🌐 Modern Ajax Made Simple XMLHttpRequest? 10 lines for simple GET? Callback hell? Fetch API is promise-based, clean syntax, built-in JSON parsing. Modern Ajax the right way. The Old Way (XMLHttpRequest) // ❌ XMLHttpRequest – Verbose and ugly const xhr = new XMLHttpRequest(); xhr.open(‘GET’, ‘https://api.example.com/users’); xhr.onload = function() { if (xhr.status === 200) { const […]
Category: Ajax
Ajax: Use AbortController to Cancel Pending Requests
🚫 Cancel Requests Before They Complete User types fast, sends 10 search requests. All 10 return, UI flickers. AbortController cancels outdated requests. The Problem // ❌ Search on every keystroke – race condition! searchInput.addEventListener(‘input’, async (e) => { const results = await fetch(`/api/search?q=${e.target.value}`); const data = await results.json(); displayResults(data); }); // User types: “javascript” // […]
AJAX: Implement Exponential Backoff for Failed Requests
🔄 Handle Network Failures Gracefully Request fails. You retry immediately. Fails again. Server overwhelmed. Exponential backoff fixes this. The Pattern async function fetchWithRetry(url, options = {}, maxRetries = 3) { for (let i = 0; i = 500 || response.status === 429) { if (i === maxRetries) throw new Error(‘Max retries reached’); // Exponential backoff: […]
AJAX: Use fetch() timeout with AbortController
Request hangs forever. No timeout in fetch API. Need manual solution. const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); try { const response = await fetch(url, { signal: controller.signal }); clearTimeout(timeoutId); return await response.json(); } catch (error) { if (error.name === ‘AbortError’) { console.log(‘Request timeout’); } } Reusable Function: async function […]
AJAX: Use FormData to Upload Files with Progress
📤 File Upload with Progress Bar Upload files + show progress. Native browser API. No libraries. const formData = new FormData(); formData.append(‘file’, fileInput.files[0]); formData.append(‘userId’, ‘123’); const xhr = new XMLHttpRequest(); // Progress tracking xhr.upload.addEventListener(‘progress’, (e) => { const percent = (e.loaded / e.total) * 100; progressBar.style.width = percent + ‘%’; }); xhr.open(‘POST’, ‘/upload’); xhr.send(formData); With […]
Ajax: Improving Perceived Speed with Skeleton Screens
Users hate spinners. They love Skeleton Screens. It gives the illusion that the content is already there. The Strategy: While your Ajax request is pending, show a gray box that matches the shape of your final content. This reduces ‘bounce rates’ significantly.
Ajax: Mastering Request Cancellation with AbortController
If a user types fast, you don’t want 10 simultaneous API calls. You should abort the previous one before starting a new search. let controller = new AbortController(); fetch(url, { signal: controller.signal }).catch(e => { if (e.name === ‘AbortError’) console.log(‘Request Cleaned Up!’); }); // To cancel: controller.abort(); This saves server resources and prevents ‘Race Conditions’ […]
Ajax: Ensuring Data Delivery with the ‘keepalive’ Flag
When a user closes a tab, your ‘Logging’ or ‘Analytics’ Ajax call usually gets canceled. Keepalive solves this. fetch(‘/api/log’, { method: ‘POST’, body: JSON.stringify(data), keepalive: true // Request continues even after tab closes }); This is the professional way to ensure critical telemetry data reaches your server without using the old, synchronous sendBeacon.
Ajax: Building Resilient Apps with Exponential Backoff Retry Logic
Network flickers happen. If a request fails, don’t just show an error; try again—but wait longer each time to avoid overloading the server. async function fetchWithRetry(url, retries = 3, delay = 1000) { try { return await fetch(url); } catch (err) { if (retries === 0) throw err; await new Promise(r => setTimeout(r, delay)); return […]
Ajax: Using ‘priority’ to Speed Up Critical API Calls
Not all API calls are equal. Your ‘User Profile’ is more important than ‘Related Products’. fetch(‘/api/user’, { priority: ‘high’ }); fetch(‘/api/ads’, { priority: ‘low’ }); The Logic: This tells the browser which network requests to put at the front of the queue, improving the ‘Perceived Performance’ of your app.
Ajax: Handling Network Failures Gracefully with Async/Await
The biggest mistake in Ajax is not catching ‘Silent Failures’ like a 404 or 500 status code. async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP Error: ${response.status}`); return await response.json(); } catch (error) { console.error(“Safety Net caught this:”, error); } }
AJAX Fetch API: The Request Interceptor Pattern That Saved Our Auth System
🔐 The Authentication Nightmare Every API call needs an auth token. Every developer on your team copies the same 10 lines of code. Token refresh logic is duplicated 47 times across your codebase. Sound familiar? The Solution: Fetch Interceptor Pattern ❌ The Repetitive Way (47 Places) // Component A const token = localStorage.getItem(‘token’); const response […]
AJAX: Use Response Type for Automatic Data Parsing
Manually parsing response JSON is error-prone. Set responseType to let fetch handle it. Manual Parsing: const response = await fetch(url); const text = await response.text(); const data = JSON.parse(text); // Error-prone! Automatic: const response = await fetch(url); const data = await response.json(); // Automatic! // Or for blob: const blob = await response.blob(); // Or […]
Ajax: Canceling Outdated Requests with AbortController
Don’t waste bandwidth. If a user clicks a button 10 times, you should abort the previous 9 requests using AbortController. const controller = new AbortController(); fetch(url, { signal: controller.signal }); // Later… controller.abort();
Ajax: Why fetch() Doesn’t ‘Fail’ on 404s and How to Fix It
A common beginner mistake is thinking .catch() handles API errors like 404 or 500. It doesn’t! Note: fetch() only rejects on network failure. const res = await fetch(url); if (!res.ok) throw new Error(‘API Error: ‘ + res.status);
Ajax: Implementing Efficient Long Polling for Real-Time UI Updates
Can’t use WebSockets? Long polling is the professional fallback. It keeps a connection open until the server has new data, reducing HTTP overhead.
Ajax: Use Axios Interceptors for Global Error Handling and Auth
Don’t manually add tokens to every request. Centralize your logic. axios.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${localStorage.getItem(‘token’)}`; return config; });
AJAX: Use Retry Logic with Exponential Backoff for Failed Requests
Network failures happen. Retry with exponential backoff prevents overwhelming server while ensuring request eventually succeeds. Simple Retry Function: async function fetchWithRetry(url, options = {}, maxRetries = 3) { for (let i = 0; i setTimeout(resolve, delay)); } } } // Usage try { const data = await fetchWithRetry(‘/api/data’); console.log(await data.json()); } catch (error) { console.error(‘Failed […]
AJAX: Use Cache API to Serve Assets Offline Like Native App
Users lose access when offline. Cache API stores assets so app works without internet. Register Service Worker: // main.js if (‘serviceWorker’ in navigator) { navigator.serviceWorker.register(‘/sw.js’); } Service Worker (sw.js): const CACHE = ‘v1’; const ASSETS = [‘/’, ‘/styles.css’, ‘/app.js’, ‘/logo.png’]; // Install: cache assets self.addEventListener(‘install’, event => { event.waitUntil( caches.open(CACHE).then(cache => cache.addAll(ASSETS)) ); }); // […]
AJAX: Use Beacon API to Send Analytics Before Page Unload
Regular fetch() in beforeunload is unreliable – browser may cancel it. Beacon API guarantees delivery. Problem with fetch(): window.addEventListener(‘beforeunload’, () => { fetch(‘/api/analytics’, { method: ‘POST’, body: JSON.stringify(data) }); // Browser often cancels this! }); Solution – Beacon API: window.addEventListener(‘beforeunload’, () => { navigator.sendBeacon(‘/api/analytics’, JSON.stringify({ timeSpent: Date.now() – pageLoadTime, scrollDepth: getScrollDepth(), clickData: clickTracker })); // […]
AJAX: Use Server-Sent Events for Real-Time Updates Without WebSocket
WebSocket is overkill for one-way real-time updates. SSE is simpler and built-in. Server (Node.js Example): app.get(‘/events’, (req, res) => { res.setHeader(‘Content-Type’, ‘text/event-stream’); res.setHeader(‘Cache-Control’, ‘no-cache’); res.setHeader(‘Connection’, ‘keep-alive’); // Send update every 5 seconds const interval = setInterval(() => { res.write(`data: ${JSON.stringify({ time: Date.now() })}\n\n`); }, 5000); req.on(‘close’, () => clearInterval(interval)); }); Client: const eventSource = new […]
AJAX: Use Intersection Observer to Load Data on Scroll (Infinite Scroll)
Checking scroll position with events is inefficient. Intersection Observer detects when element enters viewport. Setup: const loadMoreTrigger = document.getElementById(‘load-more’); const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { loadMoreData(); // Fetch next page } }); }); observer.observe(loadMoreTrigger); async function loadMoreData() { const response = await fetch(‘/api/posts?page=’ + currentPage); const data = […]
AJAX: Use URLSearchParams to Build Query Strings Cleanly
Manually concatenating query strings is error-prone. URLSearchParams handles encoding and formatting automatically. Messy Manual Way: const query = ‘?name=’ + encodeURIComponent(name) + ‘&email=’ + encodeURIComponent(email) + ‘&age=’ + age; fetch(‘/api/users’ + query); // Easy to forget encoding, messy to read Clean URLSearchParams Way: const params = new URLSearchParams({ name: ‘John Doe’, email: ‘john@example.com’, age: 30 […]
AJAX: Use Fetch with Signal to Cancel Requests When User Navigates Away
User navigates away but old fetch requests keep running in background. Cancel them properly with AbortController. Setup: const controller = new AbortController(); fetch(‘/api/data’, { signal: controller.signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => { if (error.name === ‘AbortError’) { console.log(‘Request cancelled’); } }); // Cancel when user leaves page window.addEventListener(‘beforeunload’, () => { […]
AJAX: Use FormData to Upload Files Without jQuery
Uploading files with vanilla JavaScript is simpler than you think. FormData handles everything. HTML: <input type=”file” id=”fileInput” multiple> <button onclick=”uploadFiles()”>Upload</button> JavaScript: async function uploadFiles() { const input = document.getElementById(‘fileInput’); const formData = new FormData(); for (let file of input.files) { formData.append(‘files’, file); } const response = await fetch(‘/upload’, { method: ‘POST’, body: formData // Browser […]
Ajax Revolution: How Fetch API and Async/Await Replace jQuery.ajax()
Still using jQuery for AJAX? Modern JavaScript Fetch API with async/await is cleaner, faster, and built-in. Modern Fetch vs Old jQuery Comparison: // OLD jQuery way $.ajax({ url: ‘/api/users’, method: ‘GET’, dataType: ‘json’, success: function(data) { console.log(data); }, error: function(xhr, status, error) { console.error(error); } }); // MODERN Fetch API async function getUsers() { try […]
AJAX: Use Axios Interceptors to Automatically Retry Failed Requests
Network hiccups causing failed API requests? Axios interceptors can automatically retry failed requests before showing errors to users. Install Axios: npm install axios The Basic Retry Interceptor: import axios from ‘axios’; // Configure retry axios.interceptors.response.use( response => response, // Success – return as is async error => { const config = error.config; // If no […]
Handle AJAX Errors Properly: Retry Logic with Exponential Backoff
Your AJAX calls fail randomly due to network hiccups or server load? Implement smart retry logic that actually works. The Problem with Basic Retry: // Bad: Immediate retry can make things worse function badRetry(url, maxAttempts) { for (let i = 0; i < maxAttempts; i++) { try { return await fetch(url); } catch (error) { […]
Why Your Ajax Requests “Randomly” Fail in Production
Locally works.Production fails. Cause Preflight CORS requests. What happens Browser sends: OPTIONS /api/data Before: POST /api/data If server doesn’t handle OPTIONS → fail. Minimal fix (ASP.NET example) app.UseCors(builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); Why this matters Ajax failures are often network policy, not JS bugs.
Why AJAX Requests Randomly Fail Under Load
Works locally. Fails in production. Hidden issue Browsers limit parallel connections per origin. Fix Batch requests Use request queues Prefer a single endpoint await Promise.allSettled(requests); Why Uncontrolled parallelism = dropped requests.























