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 – The XMLHttpRequest Object

15 April 2025 | Category:

The XMLHttpRequest object is one of the earliest ways to send AJAX requests in JavaScript — to communicate with a web server without reloading the page.


What is XMLHttpRequest?

The XMLHttpRequest (XHR) object lets JavaScript send HTTP requests to servers and handle their responses asynchronously.

You can:

  • GET data from a server (read)
  • POST data to a server (send)
  • Load JSON, text, or even XML files dynamically

✅ Basic Workflow of XMLHttpRequest

  1. Create an XHR object
  2. Set up the request (method + URL)
  3. Send the request
  4. Handle the response when it’s ready

🚀 Example: Make a GET Request

<button onclick="loadUser()">Load User</button>
<p id="result"></p>

<script>
  function loadUser() {
    // 1. Create the XMLHttpRequest object
    const xhr = new XMLHttpRequest();

    // 2. Set up the request
    xhr.open("GET", "https://jsonplaceholder.typicode.com/users/1", true);

    // 3. Set up a function to handle the response
    xhr.onload = function () {
      if (xhr.status === 200) {
        const user = JSON.parse(xhr.responseText);
        document.getElementById("result").innerText = `Name: ${user.name}`;
      } else {
        document.getElementById("result").innerText = "Error loading user.";
      }
    };

    // 4. Send the request
    xhr.send();
  }
</script>

✅ Output: When the button is clicked, it fetches and displays the user’s name.


🧪 Explanation of Properties and Methods

Property/MethodDescription
xhr.open(method, url)Prepares the request
xhr.send()Sends the request to the server
xhr.responseTextHolds the response data (string)
xhr.statusHTTP status code (200 = OK)
xhr.onloadEvent triggered when response is ready
xhr.onreadystatechangeOlder way to track state changes
xhr.readyStateTracks progress (0 to 4)

📘 readyState Values

ValueMeaning
0Request not initialized
1Server connection established
2Request received
3Processing request
4Request finished and response ready ✅

🚀 Example: POST Request using XHR

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

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

const data = JSON.stringify({
  title: "Hello",
  body: "This is a post",
  userId: 1
});

xhr.send(data);

This sends JSON data to the server.


🆚 XMLHttpRequest vs Fetch API

FeatureXMLHttpRequestFetch API
SyntaxVerboseClean & Promise-based
Error HandlingManual.catch() supported
Modern Usage❌ Outdated✅ Recommended

✅ Summary

  • XMLHttpRequest is the traditional way to make AJAX requests.
  • Still useful to understand, especially for legacy code.
  • For modern apps, fetch() is easier and cleaner.