Chapter 31: AJAX Examples

AJAX Examples, written as if I am your patient teacher sitting next to you.

We will go slowly and thoroughly, building understanding step by step. I will show you several progressively more realistic examples, explain every line, point out common mistakes, show what the network looks like, and explain why we write it this way in real projects (2025–2026 reality).

1. Very First Example – The absolute simplest AJAX GET

Goal: Click a button → get a message from the server → show it on the page (no reload)

HTML

What you see in browser developer tools (F12 → Network tab):

  • A request appears named hello-world
  • Method: GET
  • Status: 200 OK
  • Response headers include Content-Type: application/json
  • Response body contains the echoed “hello-world” wrapped in JSON

Important lessons from this first example:

  • xhr.open() prepares the request
  • xhr.send() actually sends it
  • xhr.onload fires when complete (readyState 4)
  • Always check xhr.status — 200–299 = success
  • onerror catches network problems (offline, DNS error, blocked by CORS…)

2. Example 2 – Using modern fetch (what you should write today)

HTML

Why fetch is better (2025–2026 standard):

  • Promise-based → easy await
  • Cleaner syntax
  • response.ok is very convenient
  • Built-in browser API — no need for libraries in most cases

3. Example 3 – Real-world style: Search with loading state & error handling

HTML

Key professional features here:

  • Debounce – wait until user stops typing
  • Loading state – shows “Searching…”
  • Error handling – nice message if something fails
  • encodeURIComponent – safe for special characters

4. Example 4 – POST with JSON (very common modern pattern)

HTML

Summary – What we learned across these examples

Pattern When to use it Key technique
Simple GET Load static data, configs, messages fetch(url)
Search / autocomplete Live filtering as user types input event + debounce
Form POST (JSON) Login, registration, comments, orders fetch(…, {method:’POST’, body})
Loading + error states All real applications try/catch, show loading message

Final 2025–2026 advice

  • Use fetch + async/await for almost everything new
  • Always handle errors — users hate silent failures
  • Add loading indicators — even 300 ms feels long without feedback
  • Debounce search inputs (300–600 ms) — saves server load
  • Validate on client before sending (empty fields, email format…)
  • Never trust client data — validate again on server

Would you like to go deeper into one of these realistic directions?

  • Add loading spinner animation
  • Show “No results found” nicely
  • Click outside to close suggestions
  • Product details modal after selection
  • Add to cart (session or real database)
  • Pagination (“Show more” button)

Just tell me which one you want next! 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *