Chapter 24: AJAX Request

1. The big picture: What does “sending a request to a server” mean in AJAX?

When we say AJAX sends a request to a server, we mean:

JavaScript code running inside the browser quietly opens a network connection to a server (the same server that served the page, or a different one), asks for something or sends something, waits for an answer, and then uses that answer to update the current page without reloading.

The most important thing to understand first:

The browser is not reloading the page. It is making a separate HTTP request in the background — exactly like when you type a URL in a new tab, but invisible to the user.

2. Three main modern ways to send a request in 2025–2026

Method How old? Style today Ease of use Promise-based? Still used directly? Recommendation 2025–2026
XMLHttpRequest (XHR) 1999–2005 Classic / old-school Medium No Yes (legacy code) Understand it, but avoid
fetch 2015–2017 Modern standard High Yes Very widely used Primary choice
axios (library) ~2014 Very popular helper Very high Yes Very common Excellent for most projects

Today most developers use fetch or axios. But you still need to understand XMLHttpRequest because:

  • Many old tutorials use it
  • Many existing codebases still use it
  • Some very specific behaviors (upload progress, older CORS tricks) are easier with XHR

3. Step-by-step: Sending a request with XMLHttpRequest (classic way)

HTML

6. What you should notice while testing

  1. No page reload — only the small box changes
  2. Network tab (F12 → Network) shows a separate request
  3. Status codes are visible (200 = OK, 404 = not found…)
  4. POST sends body (you can see it in network tab)
  5. Errors are handled gracefully

7. Quick Summary – Sending a Request with XMLHttpRequest

Action Code pattern
Create object new XMLHttpRequest()
Set method & URL xhr.open(“GET”/”POST”, url, true)
Add headers (JSON, auth…) xhr.setRequestHeader(“Content-Type”, “application/json”)
Send GET xhr.send()
Send POST / PUT xhr.send(JSON.stringify(data))
Handle success xhr.onload = … → check xhr.status 200–299
Handle network error xhr.onerror = …

8. Modern recommendation (2025–2026)

Use fetch instead for new code — it’s cleaner, Promise-based, and built-in:

JavaScript

But knowing XMLHttpRequest is still valuable because:

  • You’ll find it in legacy code
  • Some tutorials still use it
  • Certain features (fine-grained upload progress, older IE compatibility) are easier with XHR

Would you like to continue with one of these next?

  • Full POST form submission with XMLHttpRequest
  • File upload with progress bar using XHR
  • How to automatically parse JSON with XHR
  • Comparison table: XMLHttpRequest vs fetch vs axios
  • Handling CORS, timeout, abort
  • Converting old XHR code to modern fetch

Just tell me what you want to dive deeper into! 😊

You may also like...

Leave a Reply

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