HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

The XMLHttpRequest Object

The XMLHttpRequest (XHR) object is the core of AJAX. It is a built-in browser object that allows you to make HTTP requests in JavaScript without having to refresh the page.


XHR Lifecycle Observer

Click the button below to trigger a real request. Watch how the readyState changes from 0 to 4 in real-time:

0: UNSENT
1: OPENED
2: HEADERS
3: LOADING
4: DONE
Ready to observe...

Creating an XHR Object

All modern browsers have a built-in XMLHttpRequest object.

const xhttp = new XMLHttpRequest();

Common Methods

Method Description
open(method, url, async) Specifies the type of request.
send() Sends the request to the server.
abort() Cancels the current request.
getResponseHeader() Returns specific header information.

XHR Properties

Property values change as a request progresses:

  • onreadystatechange: Defines a function to be called when the readyState property changes.
  • readyState: Holds the status of the XMLHttpRequest (0-4).
  • status: Returns the status-number of a request (e.g. 200: "OK", 404: "Not Found").
  • responseText: Returns the response data as a string.

The readyState Property

The readyState property holds the status of the XMLHttpRequest:

  • 0: request not initialized
  • 1: server connection established
  • 2: request received
  • 3: processing request
  • 4: request finished and response is ready
Tip: You only want to process the data when readyState is 4 AND status is 200 (Successful).

Key Points to Remember

  • The XMLHttpRequest object is used to exchange data with a server.
  • Use open() and send() to initiate requests.
  • readyState 4 means the data is fully loaded.
  • status 200 means the request was successful.
  • It works asynchronously by default.