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: JavaScript

Ajax / JavaScript

AJAX “Works Once, Then Fails” — Cached POST Response

- 14.12.25 - ErcanOPAK comment on AJAX “Works Once, Then Fails” — Cached POST Response

Some browsers cache aggressively. ✅ Fix fetch(url, { method: ‘POST’, cache: ‘no-store’ }); Especially important for forms authentication dynamic APIs

Read More
JavaScript

JS Memory Leaks — Forgotten Event Listeners

- 14.12.25 - ErcanOPAK comment on JS Memory Leaks — Forgotten Event Listeners

Single-page apps suffer badly from this. ❌ window.addEventListener(‘resize’, handler); ✅ window.removeEventListener(‘resize’, handler); Always clean up listeners on unmount or destroy.

Read More
Ajax / JavaScript

AJAX Requests Fail Randomly? CSRF Token Missing

- 13.12.25 - ErcanOPAK comment on AJAX Requests Fail Randomly? CSRF Token Missing

POST requests fail silently without CSRF token. ✅ Fix headers: { ‘X-CSRF-TOKEN’: token } Common victims Laravel Django ASP.NET MVC

Read More
JavaScript

JS “await” Inside forEach Is a Bug

- 13.12.25 - ErcanOPAK comment on JS “await” Inside forEach Is a Bug

This does NOT work: items.forEach(async item => { await process(item); }); ✅ Correct Patterns for (const item of items) { await process(item); } or parallel: await Promise.all(items.map(process));  

Read More
JavaScript

JS “Object Mutation Side Effects” — The Hidden Reference Bug

- 12.12.25 - ErcanOPAK comment on JS “Object Mutation Side Effects” — The Hidden Reference Bug

const a = { x: 5 }; const b = a; b.x = 999; Now a.x is also 999.This breaks apps everywhere. ✔ Fix: Clone before modifying const b = structuredClone(a); or: const b = { …a };  

Read More
Ajax / JavaScript

AJAX “POST Works Locally but Not in Production” — HTTPS Mixed Content

- 11.12.25 - ErcanOPAK comment on AJAX “POST Works Locally but Not in Production” — HTTPS Mixed Content

Local: HTTPProd: HTTPSBrowser blocks insecure AJAX calls with no error. ✔ Fix Always use relative URLs: $.post(‘/api/users’, data); Avoid: $.post(‘http://localhost/api/users’, data); // ❌  

Read More
JavaScript

JS “setInterval Drift” — Why Your Timers Run Slower Over Time

- 11.12.25 - ErcanOPAK comment on JS “setInterval Drift” — Why Your Timers Run Slower Over Time

setInterval accumulates drift because execution time is included. ✔ Fix: Self-adjusting timer const start = Date.now(); let count = 0; function tick() { count++; const next = start + count * 1000; setTimeout(tick, next – Date.now()); } tick(); Accurate to the millisecond.

Read More
Ajax / JavaScript

AJAX “POST Suddenly Fails” — The Missing Content-Type Header

- 09.12.25 - ErcanOPAK comment on AJAX “POST Suddenly Fails” — The Missing Content-Type Header

Many backends reject requests silently. ✔ Fix: $.ajax({ method: “POST”, url: “/api/data”, contentType: “application/json”, data: JSON.stringify({ id: 1 }) }); Missing contentType = backend can’t parse payload.

Read More
JavaScript

JS “Undefined Errors in Loops” — The Closure Trap

- 09.12.25 - ErcanOPAK comment on JS “Undefined Errors in Loops” — The Closure Trap

Typical bug: for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), 100); } Output: 5 5 5 5 5 Because var is function-scoped. ✔ Fix for (let i = 0; i < 5; i++) { setTimeout(() => console.log(i), 100); } Or: setTimeout(((x)=>()=>console.log(x))(i), 100);  

Read More
Ajax / JavaScript

AJAX “Stale Data” — Browser Caching GET Requests Deeply

- 08.12.25 - ErcanOPAK comment on AJAX “Stale Data” — Browser Caching GET Requests Deeply

Even server changes don’t update responses. ✔ Fix $.ajax({ url: “/api/data”, cache: false }); or fetch: fetch(“/api/data”, { cache: “no-store” }); Instantly fixes “old response stuck” issue.

Read More
JavaScript

JS “Unexpected NaN” — The Invisible Type Coercion Trap

- 08.12.25 - ErcanOPAK comment on JS “Unexpected NaN” — The Invisible Type Coercion Trap

Common bug: “5” – “2” // works => 3 “5” + “2” // ’52’ “5” * “hi” // NaN JS coerces AND behaves inconsistently. ✔ Life-Saving Fix Always convert: Number(value) or parseInt(value, 10) 💡 Bonus Trap parseInt(“08”) returns 8 but “08” == 8 is true → chaos.

Read More
Ajax / JavaScript

AJAX Cache Nightmare — Why Your GET Requests Don’t Update

- 07.12.25 - ErcanOPAK comment on AJAX Cache Nightmare — Why Your GET Requests Don’t Update

Browsers cache GET requests aggressively. ✔ Life-Saving Fix $.ajax({ url: ‘/api/data’, cache: false }); Under the hood, jQuery adds:?_={timestamp} → bypasses cache. 💡 If using fetch: fetch(‘/api/data’, { cache: ‘no-store’ });  

Read More
JavaScript

JS “Debounce vs Throttle” — Why Your Search Bar Lags

- 07.12.25 - ErcanOPAK comment on JS “Debounce vs Throttle” — Why Your Search Bar Lags

Real problem:Search inputs trigger too many backend calls. ✔ Debounce (use for search) function debounce(fn, delay){ let timeout; return (…args)=>{ clearTimeout(timeout); timeout = setTimeout(()=>fn(…args), delay); }; } ✔ Throttle (use for scroll/resize) function throttle(fn, delay){ let last = 0; return (…args)=>{ const now = Date.now(); if(now – last >= delay){ last = now; fn(…args); } […]

Read More
JavaScript

JavaScript Event Loop Misconceptions — Why setTimeout(fn, 0) Is NOT Instant

- 06.12.25 - ErcanOPAK comment on JavaScript Event Loop Misconceptions — Why setTimeout(fn, 0) Is NOT Instant

Many devs think: setTimeout(() => console.log(“hi”), 0); runs immediately. It does NOT. 🔍 Why? It is put into the task queue, which only runs after: microtasks (Promise callbacks) current call stack render steps Example Promise.resolve().then(() => console.log(“promise”)); setTimeout(() => console.log(“timeout”), 0); // Output: // promise // timeout 💡 Why This Matters Debugging race conditions Handling […]

Read More
HTML / JavaScript

Service Workers — Offline-First Apps Made Easy

- 06.12.25 - ErcanOPAK comment on Service Workers — Offline-First Apps Made Easy

Service Workers let your site work offline, cache assets, and load instantly. navigator.serviceWorker.register(‘/service-worker.js’); ✨ What You Get ⚡ Near-instant load time 📦 Cached static assets 📡 Offline browsing 🔋 Reduced server load 💡 Combine with “cache-first” strategies for ultimate speed.

Read More
JavaScript

Debounce vs Throttle — The UI Performance Problem Everyone Gets Wrong

- 06.12.25 - ErcanOPAK comment on Debounce vs Throttle — The UI Performance Problem Everyone Gets Wrong

🎯 Debounce Trigger after user stops typing. Great for: Search boxes Auto-suggest Validation 🌀 Throttle Trigger every X ms, no matter what. Great for: Scroll events Resize events Mouse move Quick Example const debounced = debounce(fn, 300); const throttled = throttle(fn, 200); 💡 Using the wrong one leads to janky UI & wasted CPU.

Read More
JavaScript

JavaScript Web Workers — Real Multithreading for Heavy Tasks

- 06.12.25 - ErcanOPAK comment on JavaScript Web Workers — Real Multithreading for Heavy Tasks

Web Workers allow JS to run CPU-heavy tasks off the main thread. const worker = new Worker(“worker.js”); worker.postMessage({ action: “process” }); 💥 Why Use Them 🧵 Prevent UI blocking 🚀 Faster data processing 📸 Smooth animations 🧩 Perfect for image, crypto & data tasks

Read More
Development / JavaScript

How to format date in Javascript

- 09.09.24 - ErcanOPAK comment on How to format date in Javascript

function formatDate(date) { var d = new Date(date), month = ” + (d.getMonth() + 1), day = ” + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = ‘0’ + month; if (day.length < 2) day = ‘0’ + day; return [day, month, year].join(‘.’); } OUTPUT: 19.05.2024 NOTE: If you make the return like […]

Read More
ASP.Net MVC / ASP.Net WebForms / Bootstrap / JavaScript

How to change star rating color on mouseover/out, mouseenter/leave with Javascript

- 20.06.23 - ErcanOPAK comment on How to change star rating color on mouseover/out, mouseenter/leave with Javascript

function onMouseEnter(index){ var star = document.getElementsByClassName(“starClass”); var j; for(j = 0; j < fa.length; j++){ if(j < index){ star[j].style.color = “orange”; } else{ star[j].style.color = “#ccc”; } } } function onMouseOut(){ var star = document.getElementsByClassName(“starClass”); var k; for(k = 0; k < fa.length; k++){ star[k].style.color = “#ccc”; } }

Read More
ASP.Net MVC / ASP.Net WebForms / JavaScript

How to disable ASP.Net button after click to prevent double clicking

- 13.01.23 | 20.03.23 - ErcanOPAK comment on How to disable ASP.Net button after click to prevent double clicking

Let’s say you have 2 buttons on your web page. <form id=”form1″ runat=”server”> <asp:Button ID=”Button1″ runat=”server” Text=”Button1″ OnClick=”Button1_Clicked” /> <asp:Button ID=”Button2″ runat=”server” Text=”Button2″ /> </form> Scenario 1: Disabling the specific button <script type=”text/javascript”> function DisableButton() { document.getElementById(“<%=Button1.ClientID %>”).disabled = true; } window.onbeforeunload = DisableButton; </script> The DisableButton JavaScript function is used for disabling specific Button when Clicked. […]

Read More
ASP.Net MVC / ASP.Net WebForms / HTML / JavaScript

How to use client-side function on checkbox or any asp.net component

- 10.11.22 - ErcanOPAK comment on How to use client-side function on checkbox or any asp.net component

Here is the Asp part: <label for=”chkCondition”> <asp:CheckBox ID=”chkCondition” Text=”Should i show the div?” runat=”server” onclick=”ShowHideDiv(this)” /> </label> <hr /> <div id=”divToShowOrHide” style=”display: none”> this div will be shown regarding the checkbox checked status. <asp:TextBox ID=”myTextBox” runat=”server” /> </div> And here is the Javascript part: <script type=”text/javascript”> function ShowHideDiv(chkCondition) { var divToShowOrHide = document.getElementById(“divToShowOrHide”); divToShowOrHide.style.display […]

Read More
ASP.Net MVC / JavaScript

How to remove searching, filtering, ordering and info from Asp.NET MVC Datatable

- 15.09.22 - ErcanOPAK comment on How to remove searching, filtering, ordering and info from Asp.NET MVC Datatable

var table = $(“#datatable”).DataTable({ “paging”: false, “ordering”: false, “searching”: false, “info”: false });  

Read More
ASP.Net MVC / ASP.Net WebForms / JavaScript

How to get session value in Javascript

- 16.04.22 - ErcanOPAK comment on How to get session value in Javascript

<script> let mySession = ‘<%= Session[“SessionName”].ToString() %>’; //use your session … console.log(mySession); alert(mySession); </script>  

Read More
ASP.Net MVC / ASP.Net WebForms / HTML / JavaScript

Search text through Divs in Javascript

- 29.12.21 - ErcanOPAK comment on Search text through Divs in Javascript

<table align=”center” width=”20%”> <tr> <td style=”padding-right: 10px”> <input type=”text” id=”Search” onkeyup=”myFunction()” placeholder=”Please enter a search term..” title=”Type in a name”> </td> </tr> </table> <br> <div class=”target”> This is my DIV element. </div> <div class=”target”> This is another Div element. </div> <div class=”target”> Can you find me? </div> <script> function myFunction() { var input = document.getElementById(“Search”); […]

Read More
JavaScript

How replace characters with asterisks (*) except first characters

- 31.10.21 - ErcanOPAK comment on How replace characters with asterisks (*) except first characters

const theName = “Vincent van Gogh”; function hideWord(word) { if (word.length < 2) return word; return word.substring(0, 1) + ‘*’.repeat(word.length-1); } console.log(theName.split(” “).map(hideWord).join(” “)); OUTPUT: V****** v** G*** You could also wrap the whole lot in a function if you wanted to be able to call it from multiple places and avoid redefining it. function […]

Read More
JavaScript

Smart way to truncate long strings in Javascript

- 28.10.21 - ErcanOPAK comment on Smart way to truncate long strings in Javascript

Let’s say we want to truncate long strings (length > 250): short = long.replace(/(.{250})..+/, “$1&hellip;”); or short = long.replace(/(.{250})..+/, “$1…”);  

Read More
ASP.Net MVC / JavaScript

Populating Javascript array with Model in ASP.Net MVC Razor

- 23.10.21 - ErcanOPAK comment on Populating Javascript array with Model in ASP.Net MVC Razor

We just need to loop through the razor collection to populate the Javascript array as below: @foreach (var item in Model) { @:$(function () { @:$(“#map”).googleMap(); @:$(“#map”).addMarker({ @:coords:[@item.Latitude], @:title: `@item.City, @item.District`, @:text: `@item.Address` @:}); @:}); }  

Read More
ASP.Net MVC / C# / JavaScript

Pass model from Razor view to JavaScript

- 23.10.21 - ErcanOPAK comment on Pass model from Razor view to JavaScript

Let’s say you send a model called “MyModel” from controller to view. In Controller: … var result = new MyModel() { Id = 1, Name = “Ercan”, FavoriteTeam = “Galatasaray”, FavoriteGame = “Half Life Series” } return View(result); … and now we will send this model which comes with result to Javascript via setName function: […]

Read More
JavaScript

Add and Remove classes from element in Javascript

- 23.10.21 - ErcanOPAK comment on Add and Remove classes from element in Javascript

classList is pretty smart and the most modern system of manipulating CSS class names in elements via JavaScript. Adding class name: const element = document.getElementById(‘txtMyText’); element.classList.add(‘myClass’); Removing class name: const element = document.getElementById(‘txtMyText’); element.classList.remove(‘myClass’); Removing multiple class names: const element = document.getElementById(‘txtMyText’); element.classList.remove(‘myClass1’, ‘myClass2’) Thanks to clubmate.fi

Read More
JavaScript

Split and Join in Javascript

- 09.10.21 - ErcanOPAK comment on Split and Join in Javascript

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array.  The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method’s call. Syntax split() split(separator) split(separator, limit) Return value An Array of strings, split at each point where the separator occurs […]

Read More
Page 5 of 6
« Previous 1 2 3 4 5 6 Next »

Posts pagination

« Previous 1 … 3 4 5 6 Next »
June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

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

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

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