Tutorials Logic, IN info@tutorialslogic.com

XMLHttpRequest in AJAX XHR

XMLHttpRequest in AJAX XHR

XMLHttpRequest in AJAX XHR is an important AJAX topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem XMLHttpRequest in AJAX XHR solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of XMLHttpRequest in AJAX XHR should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

XMLHttpRequest in AJAX XHR should be studied as a practical AJAX lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the ajax > xmlhttprequest page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

What is XMLHttpRequest?

XMLHttpRequest (XHR) is a built-in browser object that enables JavaScript to make HTTP requests to a server without reloading the page. It was originally developed by Microsoft for Internet Explorer 5 and later standardized by the W3C. Despite its name, XHR can transfer any type of data - not just XML.

Creating and Using XMLHttpRequest

Creating and Using XMLHttpRequest
// 1. Create the XHR object
const xhr = new XMLHttpRequest();

// 2. Configure: open(method, url, async)
//    method: 'GET', 'POST', 'PUT', 'DELETE', etc.
//    url: the endpoint to call
//    async: true (default) = non-blocking
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

// 3. Set up the response handler
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    const post = JSON.parse(xhr.responseText);
    console.log('Title:', post.title);
  } else {
    console.error('Request failed with status:', xhr.status);
  }
};

// 4. Handle network errors
xhr.onerror = function () {
  console.error('Network error occurred');
};

// 5. Send the request
xhr.send();

readyState Values

The readyState property tracks the state of the XHR request through its lifecycle. It changes from 0 to 4 as the request progresses.

Value State Description
0 UNSENT Object created, open() not called yet.
1 OPENED open() called, request not sent yet.
2 HEADERS_RECEIVED send() called, response headers received.
3 LOADING Response body is being downloaded.
4 DONE Request complete (success or failure).

onreadystatechange Handler

onreadystatechange Handler
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/users', true);

// onreadystatechange fires every time readyState changes
xhr.onreadystatechange = function () {
  console.log('readyState:', xhr.readyState);

  if (xhr.readyState === XMLHttpRequest.DONE) { // === 4
    if (xhr.status === 200) {
      const data = JSON.parse(xhr.responseText);
      console.log('Data:', data);
    } else {
      console.error('Error:', xhr.status, xhr.statusText);
    }
  }
};

xhr.send();

Timeout and Abort

You can set a timeout (in milliseconds) to automatically cancel a request that takes too long. The abort() method lets you cancel a request programmatically.

Timeout, Abort, and withCredentials

Timeout, Abort, and withCredentials
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/slow-endpoint', true);

// Cancel request if it takes more than 5 seconds
xhr.timeout = 5000;

xhr.ontimeout = function () {
  console.warn('Request timed out after 5 seconds');
};

// Send cookies and auth headers with cross-origin requests
xhr.withCredentials = true;

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};

xhr.send();

// Manually cancel the request (e.g., user navigates away)
document.getElementById('cancel-btn').addEventListener('click', () => {
  xhr.abort();
  console.log('Request aborted');
});

XHR Progress Events and Upload Tracking

XHR Progress Events and Upload Tracking
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);

// Track download progress
xhr.onprogress = function (event) {
  if (event.lengthComputable) {
    const percent = Math.round((event.loaded / event.total) * 100);
    console.log(`Download: ${percent}%`);
  }
};

// Track upload progress
xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    const percent = Math.round((event.loaded / event.total) * 100);
    document.getElementById('progress-bar').style.width = percent + '%';
  }
};

xhr.onload = () => console.log('Upload complete:', xhr.status);
xhr.onerror = () => console.error('Upload failed');

const formData = new FormData(document.getElementById('upload-form'));
xhr.send(formData);

Detailed Learning Notes for XMLHttpRequest in AJAX XHR

When studying XMLHttpRequest in AJAX XHR, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In AJAX, XMLHttpRequest in AJAX XHR becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

XMLHttpRequest in AJAX XHR state check

XMLHttpRequest in AJAX XHR state check
const state = { topic: "XMLHttpRequest in AJAX XHR", ready: true };
if (state.ready) {
  console.log(state.topic + ": render or run the normal path");
}

XMLHttpRequest in AJAX XHR fallback check

XMLHttpRequest in AJAX XHR fallback check
const response = null;
const message = response?.message ?? "XMLHttpRequest in AJAX XHR: show a clear fallback";
console.log(message);
Key Takeaways
  • Explain the purpose of XMLHttpRequest in AJAX XHR before memorizing syntax.
  • Run or trace one small AJAX example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for XMLHttpRequest in AJAX XHR.
  • Write the rule in your own words after checking the example.
  • Connect XMLHttpRequest in AJAX XHR to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing XMLHttpRequest in AJAX XHR without the situation where it is useful.
RIGHT Connect XMLHttpRequest in AJAX XHR to a concrete AJAX task.
Purpose makes syntax easier to recall.
WRONG Testing XMLHttpRequest in AJAX XHR only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to XMLHttpRequest in AJAX XHR.
Evidence keeps debugging focused.
WRONG Memorizing XMLHttpRequest in AJAX XHR without the situation where it is useful.
RIGHT Connect XMLHttpRequest in AJAX XHR to a concrete AJAX task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to XMLHttpRequest in AJAX XHR, then fix it and explain the fix.
  • Summarize when to use XMLHttpRequest in AJAX XHR and when another approach is better.
  • Write a small example that uses XMLHttpRequest in AJAX XHR in a realistic AJAX scenario.
  • Change one important value in the XMLHttpRequest in AJAX XHR example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in AJAX, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Next Step

Keep the topic moving from lesson to practice.

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.