JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

AJAX – XMLHttpRequest Tutorial

15 April 2025 | Category:

What is XMLHttpRequest?

XMLHttpRequest (also known as XHR) is a JavaScript object that allows the browser to communicate with a server in the background without reloading the entire page.

It is a core part of AJAX (Asynchronous JavaScript and XML).

đź§  With XHR, you can fetch data (GET) or send data (POST) without refreshing your webpage.


âś… When to Use XMLHttpRequest?

  • Loading user data from an API
  • Submitting a form without reloading
  • Live search suggestions
  • Chat apps, notifications, dynamic content loading

đź§° Basic Syntax

const xhr = new XMLHttpRequest();         // 1. Create the object
xhr.open("GET", "url", true);            // 2. Configure the request
xhr.onload = function () {               // 3. Define what to do when response arrives
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();                              // 4. Send the request

💡 XHR Lifecycle – readyState values

ValueDescription
0Request not initialized
1Server connection established
2Request received
3Processing request
4Request finished and response is ready âś…

🚀 Example 1: GET Request (Fetch Data from Server)

<button onclick="loadData()">Get User</button>
<p id="output"></p>

<script>
function loadData() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "https://jsonplaceholder.typicode.com/users/1", true);

  xhr.onload = function () {
    if (xhr.status === 200) {
      const user = JSON.parse(xhr.responseText);
      document.getElementById("output").innerText = `Name: ${user.name}`;
    }
  };

  xhr.send();
}
</script>

âś… This fetches data from an API and updates the HTML without reloading the page.


🚀 Example 2: POST Request (Send Data to Server)

const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = function () {
  if (xhr.status === 201) {
    console.log("Response:", xhr.responseText);
  }
};

const data = JSON.stringify({
  title: "New Post",
  body: "This is some sample data",
  userId: 1
});

xhr.send(data);

âś… This sends JSON data to the server.


đź“‘ Key XHR Properties

PropertyDescription
xhr.responseTextText response from server
xhr.statusHTTP status code (200 = OK)
xhr.readyStateCurrent state of request
xhr.onreadystatechangeRuns at each change in readyState
xhr.onloadRuns when request is complete (readyState 4)

🆚 XHR vs Fetch API

FeatureXMLHttpRequestfetch() (Modern)
SyntaxVerboseCleaner (promise-based)
Error HandlingManualEasier with .catch()
SupportAll browsersAll modern browsers
Usage TodayLegacy codeRecommended for new code

📝 Summary

  • XMLHttpRequest is a core tool for making AJAX requests.
  • Use .open() to prepare the request and .send() to send it.
  • Use .onload or .onreadystatechange to handle the response.
  • Mostly replaced by the Fetch API, but still important to know.