Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Category: Ajax

Ajax

Ajax: Use Fetch API Instead of XMLHttpRequest for Clean Async Requests

- 30.03.26 - ErcanOPAK comment on Ajax: Use Fetch API Instead of XMLHttpRequest for Clean Async Requests

🌐 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 […]

Read More
Ajax

Ajax: Use AbortController to Cancel Pending Requests

- 22.03.26 - ErcanOPAK comment on 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” // […]

Read More
Ajax

AJAX: Implement Exponential Backoff for Failed Requests

- 19.03.26 - ErcanOPAK comment on 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: […]

Read More
Ajax

AJAX: Use fetch() timeout with AbortController

- 19.03.26 | 19.03.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

AJAX: Use FormData to Upload Files with Progress

- 19.03.26 | 19.03.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

Ajax: Improving Perceived Speed with Skeleton Screens

- 01.03.26 - ErcanOPAK comment on 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.

Read More
Ajax

Ajax: Mastering Request Cancellation with AbortController

- 01.03.26 - ErcanOPAK comment on 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’ […]

Read More
Ajax

Ajax: Ensuring Data Delivery with the ‘keepalive’ Flag

- 01.03.26 - ErcanOPAK comment on 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.

Read More
Ajax

Ajax: Building Resilient Apps with Exponential Backoff Retry Logic

- 28.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

Ajax: Using ‘priority’ to Speed Up Critical API Calls

- 28.02.26 - ErcanOPAK comment on 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.

Read More
Ajax

Ajax: Handling Network Failures Gracefully with Async/Await

- 28.02.26 - ErcanOPAK comment on 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); } }

Read More
Ajax

AJAX Fetch API: The Request Interceptor Pattern That Saved Our Auth System

- 23.02.26 | 23.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

AJAX: Use Response Type for Automatic Data Parsing

- 22.02.26 | 22.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

Ajax: Canceling Outdated Requests with AbortController

- 21.02.26 - ErcanOPAK comment on 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();

Read More
Ajax

Ajax: Why fetch() Doesn’t ‘Fail’ on 404s and How to Fix It

- 21.02.26 - ErcanOPAK comment on 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);

Read More
Ajax

Ajax: Implementing Efficient Long Polling for Real-Time UI Updates

- 21.02.26 - ErcanOPAK comment on 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.

Read More
Ajax

Ajax: Use Axios Interceptors for Global Error Handling and Auth

- 21.02.26 - ErcanOPAK comment on 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; });

Read More
Ajax

AJAX: Use Retry Logic with Exponential Backoff for Failed Requests

- 21.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

AJAX: Use Cache API to Serve Assets Offline Like Native App

- 17.02.26 - ErcanOPAK comment on 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)) ); }); // […]

Read More
Ajax

AJAX: Use Beacon API to Send Analytics Before Page Unload

- 16.02.26 - ErcanOPAK comment on 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 })); // […]

Read More
Ajax

AJAX: Use Server-Sent Events for Real-Time Updates Without WebSocket

- 15.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

AJAX: Use Intersection Observer to Load Data on Scroll (Infinite Scroll)

- 15.02.26 - ErcanOPAK comment on 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 = […]

Read More
Ajax

AJAX: Use URLSearchParams to Build Query Strings Cleanly

- 14.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

AJAX: Use Fetch with Signal to Cancel Requests When User Navigates Away

- 13.02.26 - ErcanOPAK comment on 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’, () => { […]

Read More
Ajax

AJAX: Use FormData to Upload Files Without jQuery

- 13.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

Ajax Revolution: How Fetch API and Async/Await Replace jQuery.ajax()

- 05.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax

AJAX: Use Axios Interceptors to Automatically Retry Failed Requests

- 03.02.26 - ErcanOPAK comment on 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 […]

Read More
Ajax / JavaScript

Handle AJAX Errors Properly: Retry Logic with Exponential Backoff

- 01.02.26 | 01.02.26 - ErcanOPAK comment on 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) { […]

Read More
Ajax

Why Your Ajax Requests “Randomly” Fail in Production

- 31.01.26 - ErcanOPAK comment on 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.

Read More
Ajax / JavaScript

Why AJAX Requests Randomly Fail Under Load

- 30.01.26 - ErcanOPAK comment on 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.

Read More
Page 1 of 3
1 2 3 Next »

Posts navigation

Older posts
April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • Find numbers with more than two decimal places in SQL (448)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com