XMLHttpRequest in AJAX: How It Works and the Fetch Alternative

XMLHttpRequest (XHR) is a browser API for sending HTTP requests without reloading the whole page. Modern browsers also provide the fetch() API, which usually gives new code a simpler promise-based interface.

XMLHttpRequest communication between a browser and a server

Fetch API example

This example calls the GET processor used in the AJAX GET tutorial. The query value is encoded with URLSearchParams, the HTTP status is checked, and the plain-text response is returned.

async function loadMessage(name) {
  const params = new URLSearchParams({ txt: name });
  const response = await fetch(`ajax-get-testck.php?${params}`);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  return response.text();
}

Creating an XMLHttpRequest object

In current browsers, creating an XHR object is direct:

const request = new XMLHttpRequest();

You do not need browser-specific object creation or ActiveX fallbacks for current web development.

Sending a GET request with XMLHttpRequest

The same request used above can be written with XHR. Encode the query parameter, check the HTTP status, and handle network failures.

function loadMessageWithXHR(name) {
  const params = new URLSearchParams({ txt: name });
  const request = new XMLHttpRequest();

  request.open('GET', `ajax-get-testck.php?${params}`, true);

  request.onload = function () {
    if (request.status >= 200 && request.status < 300) {
      console.log(request.responseText);
    } else {
      console.error(`HTTP ${request.status}`);
    }
  };

  request.onerror = function () {
    console.error('Network error');
  };

  request.send();
}

How XMLHttpRequest works

XHR acts as the browser-side request object between your JavaScript and a server endpoint. A typical request follows these steps:

  1. Create an XMLHttpRequest object.
  2. Call open() with the HTTP method and URL.
  3. Attach response and error handlers.
  4. Call send().
  5. Use the returned data only after the request completes successfully.

Fetch vs XMLHttpRequest

FeatureFetchXMLHttpRequest
Programming modelPromises / async-awaitEvent callbacks
HTTP error handlingCheck response.okCheck status
Progress eventsStreaming APIs are needed for detailed progressBuilt-in progress events are available
Existing older codebasesMay require refactoringCommon in established AJAX code

Historical browser compatibility

Very old versions of Internet Explorer created AJAX request objects through Microsoft ActiveX components. That compatibility code explains why older tutorials may contain ActiveXObject, but it is not needed in current browsers and should not be copied into new code.

Common mistakes

  • Concatenating raw user input into a URL instead of encoding query parameters.
  • Assuming every completed HTTP request is successful without checking the status.
  • Updating the page from a response before validating its format.
  • Keeping obsolete browser-detection or ActiveX branches in new code.
GET method of Form submission using Ajax
Ajax Json XML


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer