🧱 AJAX Core Technologies
Estimated reading: 3 minutes 37 views

βš™οΈ AJAX – XMLHttpRequest Object: A Complete Guide for Beginners


🧲 Introduction – Why Learn XMLHttpRequest in AJAX?

The XMLHttpRequest object is the backbone of traditional AJAX programming. Long before the fetch() API gained popularity, XMLHttpRequest allowed web pages to communicate with the server in the background, enabling partial updates without page reloads.

Even today, it remains essential for understanding how asynchronous communication works at a lower level.

🎯 In this article, you’ll learn:

  • What XMLHttpRequest is and how it works
  • Syntax and readyState lifecycle
  • Full examples of GET and POST requests
  • How to handle responses, errors, and status codes

πŸ” What Is XMLHttpRequest in AJAX? (Primary Keyword)

The XMLHttpRequest (XHR) object is a built-in JavaScript object used to exchange data with a web server without reloading the page.

It supports both synchronous and asynchronous modes and can handle:

  • Text
  • HTML
  • XML
  • JSON

🧱 Basic Syntax and Lifecycle

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true); // true = asynchronous
xhr.send();

πŸ“ˆ Lifecycle (readyState values):

ValueMeaning
0Request not initialized
1Server connection established
2Request received
3Processing request
4Request finished and response is ready βœ…

πŸ“₯ AJAX GET Request with XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    console.log("User:", data.user);
  }
};

xhr.send();

βœ… This sends a GET request to data.json and logs the user data once the response is complete.


πŸ“ AJAX POST Request with XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

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

xhr.send("name=John&email=john@example.com");

βœ… This sends form data to submit.php and updates the DOM with the server’s response.


🚨 Handling Errors in XMLHttpRequest

xhr.onerror = function () {
  console.error("Request failed.");
};

xhr.ontimeout = function () {
  console.error("Request timed out.");
};

xhr.timeout = 5000; // Set timeout to 5 seconds

βœ… Use these events to handle failures and set timeouts for slow requests.


πŸ“Š XMLHttpRequest vs fetch()

FeatureXMLHttpRequestfetch()
SyntaxVerboseCleaner (Promise-based)
Browser SupportWidely supportedModern browsers only
Error HandlingManual event handling.catch() or try/catch
Stream HandlingBasicAdvanced (ReadableStream)

🧠 Best Practices for Using XMLHttpRequest

  • βœ… Always check readyState === 4 && status === 200 before processing
  • βœ… Use setRequestHeader() when sending POST data
  • βœ… Prefer asynchronous requests for non-blocking performance
  • βœ… Use try/catch around JSON parsing
  • βœ… Consider replacing with fetch() for newer apps

πŸ“Œ Summary – Recap & Takeaways

The XMLHttpRequest object was the original driver of AJAX. Though newer APIs like fetch() exist, XMLHttpRequest is still a reliable method for sending and receiving HTTP requests asynchronously.

πŸ” Key Takeaways:

  • XMLHttpRequest enables browser-server communication without page reloads
  • It supports both GET and POST methods
  • Use onreadystatechange to handle responses
  • Use error events like onerror and ontimeout for reliability

βš™οΈ Next Steps:

  • Practice creating CRUD operations with XMLHttpRequest
  • Compare XMLHttpRequest with fetch in real projects
  • Explore XML parsing with responseXML

❓ FAQs – XMLHttpRequest in AJAX


❓ What is XMLHttpRequest used for in AJAX?
βœ… It allows JavaScript to send and receive data asynchronously from the server without reloading the webpage.


❓ What are the readyState values in XMLHttpRequest?
βœ… 0: uninitialized, 1: opened, 2: headers received, 3: loading, 4: done.


❓ How to check if an AJAX request is successful?
βœ… Check xhr.readyState === 4 and xhr.status === 200 in the onreadystatechange function.


❓ Can XMLHttpRequest send JSON data?
βœ… Yes. Set Content-Type: application/json and use JSON.stringify(data) in the send() method.


❓ Is XMLHttpRequest still supported in modern browsers?
βœ… Yes, but it’s being replaced by fetch() in most new applications due to better syntax and promise support.


Share Now :

Leave a Reply

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

Share

AJAX – XMLHttpRequest Object

Or Copy Link

CONTENTS
Scroll to Top