Browser - XMLHttpRequest (XHR) API

1 - About

The XMLHttpRequest is a web api function that performs an Aysnchronous HTTP request (You will then fetch resources (page, …).

The XMLHttpRequest is the base APIin AJAX programming as the fetch API was implemented above this function.

3 - Status

The status of an XHR request.

Value Constant Field State Description
0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.

4 - Example

4.1 - Get

With a get request

function onLoaded() {
  var data = JSON.parse(this.responseText); => (
      console.log(" "+item.price)

  • A function to handle any error

function error(err) {
  console.log('Fetch Error', err);

  • The several steps needed to send a XMLHttpRequest.

var xhRequest= new XMLHttpRequest();
xhRequest.onload = onLoaded;
xhRequest.onerror = error;'get', '', true);

4.2 - Post

  • An utility function to shows the description of the state and not the constant number

function toStateDescription(state) {
	switch(state) {
	  case XMLHttpRequest.DONE:
		return 'DONE'
	  case XMLHttpRequest.UNSENT:
		return 'UNSET';
	  case XMLHttpRequest.OPENED:
		return 'OPENED';
	  case XMLHttpRequest.HEADERS_RECEIVED:
	  case XMLHttpRequest.LOADING:
		return 'LOADING';
		throw new Error("Unknown status "+state);

  • The callback function when the state changes. It will show the request status when the state is done.

function stateListener () { 
    console.log("The state has changed to "+toStateDescription(this.readyState));
    if (this.readyState === XMLHttpRequest.DONE ) {
        if (this.status === 200) {
            console.log("The request has finished with the following status ("+this.status+" - "+this.statusText+")");
        } else {
            console.log("The request has not finished successfully. Status = ("+this.status+" - "+this.statusText+")");

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = stateListener;"POST", '', true);
xhr.setRequestHeader("Content-Type", "application/json"); // How to set a header (must be called after open)
// The send argument is the body
xhr.send('{ "event_name": "script called", "properties": { "url": "'+parent.document.URL+'", "type": "example"} }');

5 - Management

5.1 - See

In the Browser devtool, you can see the request.

Example with Chrome.


HTTP - Header (Fields)


X-Requested-With cannot be added to a cross domain request without the consent of the server via CORS.

6 - Documentation / Reference

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap