πŸ” AJAX Request & Response Lifecycle
Estimated reading: 3 minutes 51 views

⚑ AJAX – Creating XMLHttpRequest Object (Step-by-Step Guide with Examples)

🧲 Introduction – What Is XMLHttpRequest in AJAX?

AJAX (Asynchronous JavaScript and XML) allows web pages to update data asynchronously without refreshing the page. The core of AJAX is the XMLHttpRequest object, which enables data exchange between a client and a server.

This guide will walk you through how to create, configure, and use the XMLHttpRequest object to send and receive data with modern AJAX applications.


🧱 What Is XMLHttpRequest?

The XMLHttpRequest object is used to interact with servers via JavaScript. It enables:

  • Sending and receiving data in background
  • Updating parts of a webpage without full reload
  • Handling responses in formats like JSON, XML, HTML, or plain text

πŸ› οΈ How to Create XMLHttpRequest Object

βœ… Basic Syntax (Modern Browsers):

let xhr = new XMLHttpRequest();

This creates an instance of the XMLHttpRequest class in all modern browsers (Chrome, Firefox, Safari, Edge).

🧰 Compatibility with Older IE Versions (IE5, IE6):

let xhr;

if (window.XMLHttpRequest) {
  // Modern browsers
  xhr = new XMLHttpRequest();
} else {
  // Internet Explorer 5/6
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

πŸ’‘ Note: ActiveXObject is no longer used in modern development.


πŸ“€ Sending a Request to the Server

Once the object is created, you can open and send a request.

πŸ“‘ GET Request Example:

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true); // method, URL, async
xhr.send();

πŸ“© POST Request Example:

let xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=John&age=30");

πŸ” Handling Server Response

After sending the request, monitor its state using onreadystatechange:

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // Success
    console.log(xhr.responseText);
  }
};

🧠 readyState Values:

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

🧠 status Values:

Status CodeMeaning
200OK (Success)
404Not Found
500Server Error

πŸ§ͺ Full Working Example

πŸ“ HTML (index.html)

<button onclick="loadData()">Get Data</button>
<div id="output"></div>

βš™οΈ JavaScript

function loadData() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "data.txt", true);

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      document.getElementById("output").innerHTML = xhr.responseText;
    }
  };

  xhr.send();
}

πŸ§ͺ Result: Clicking the button fetches content from data.txt and displays it inside the #output div.


βœ… Best Practices for Using XMLHttpRequest

  • βœ… Use XMLHttpRequest only when you can’t use fetch() (modern alternative)
  • βœ… Always check for readyState and status before handling responses
  • βœ… Handle error states like 404 or 500 gracefully
  • βœ… Avoid blocking requests (async = false) – always use asynchronous mode
  • βœ… Consider setting request timeouts with xhr.timeout

πŸ“Œ Summary

The XMLHttpRequest object is a foundational part of AJAX development. It allows web pages to communicate with servers asynchronously and dynamically update content. While modern apps favor fetch(), understanding XMLHttpRequest helps when working with legacy systems or needing advanced control

πŸ” Key Takeaways:

  • XMLHttpRequest is the core of traditional AJAX
  • Use open() and send() to initiate requests
  • Monitor readyState and status for response handling
  • Combine with HTML/CSS to build interactive, data-driven interfaces
  • Prefer fetch() for new projects, but know XMLHttpRequest for compatibility

❓ Frequently Asked Questions (FAQ)

❓ What is XMLHttpRequest used for?

βœ… It’s used to send HTTP requests to servers and load data without refreshing the page.

❓ What’s the difference between XMLHttpRequest and fetch()?

βœ… fetch() is a newer, Promise-based alternative to XMLHttpRequest, offering cleaner syntax.

❓ Can I send POST data with XMLHttpRequest?

βœ… Yes. Set the request method to POST and use xhr.send("key=value").

❓ Does XMLHttpRequest work with JSON?

βœ… Yes. You can send and receive JSON by setting headers and parsing xhr.responseText with JSON.parse().

❓ Is XMLHttpRequest still used in 2025?

βœ… While fetch() is preferred, XMLHttpRequest is still supported in all browsers and widely used in legacy systems.


.

Share Now :

Leave a Reply

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

Share

AJAX Creating XMLHttpRequest Object

Or Copy Link

CONTENTS
Scroll to Top