Browser - XMLHttpRequest (XHR) API

Browser

About

The XMLHttpRequest is a web api function that performs an resource fetch with an Aysnchronous HTTP request

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

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.

Example

Get

With a get request

function onLoaded() {
  var data = JSON.parse(this.responseText);
  data.items.map(item => (
      console.log(item.name+" "+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;
xhRequest.open('get', '/doc/json/items.json', true);
xhRequest.send();

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'
		break;
	  case XMLHttpRequest.UNSENT:
		return 'UNSET';
		break;
	  case XMLHttpRequest.OPENED:
		return 'OPENED';
		break;
	  case XMLHttpRequest.HEADERS_RECEIVED:
		return 'HEADERS_RECEIVED';
		break;
	  case XMLHttpRequest.LOADING:
		return 'LOADING';
		break;
	  default:
		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+")");
        }
    }
}

Usage: Tracker example

Send a post as a client side tracker will do.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = stateListener;
xhr.open("POST", 'https://api.bytle.net/combo/api/v1.0/analytics/event', 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"} }');

Management

See

In the Browser devtool, you can see the request.

Example with Chrome.

Chrome Devtool Xhr Fetch Request

You can see the type of request with the X-Requested-With header.

X-Requested-With:XMLHttpRequest

Body

In the send method, you are passing the body.

If you pass:

Note that that you can overwrite the mime (content-type)

Documentation / Reference





Discover More
Chrome Devtool Xhr Fetch Request
Browser - Ajax (Asynchronous JavaScript And XML)

Asynchronous Javascript and XML (Ajax) is just a name umbrella to talk a technology that retrieve data from a server asynchronously. Ajax Every Ajax call is using: a XMLHttpRequest (XHR) request...
Browser
Browser - Fetching Resources (Request/Response)

This article is fetching (http request/response) in the browser. User agents can implement a variety of transfer protocols to fetch resources such as: HTTP : , ... Form FTP ... rendering...
Chrome Devtool Xhr Fetch Request
Browser - Web API - Fetch function

The fetch function is part of the web api function and is a AJAX call. It's one of the possibilities to fetch a resource. XMLHttpRequest (XHR) The fetch function returns a promise as response. The Fetch...
DOM - Document Loaded - onload event

The load event is an event that is fired / emitted on: an HTML element that fetch resources on the browser window when the page has finish loading. This event is a timing page load event To...
HTML - How to retrieve the data of a form with Javascript

This article shows you how to retrieve the data of a form with Javascript succesful controls You don't need to submit a form to get the values Every form object has a elements property that stores...
Chrome Devtool Har
HTTP - Request

An HTTP request is a message sent from a client to a server. It's the first part of a fetch, the second being the response. A request message has: a first line called the request...
Formdata Browser Devtool
How to use FormData and send multipart-data in the Browser (Web API )?

FormData is a web api object that represent the data of a form that should be send if the form is submited. Therefore if you have a checkbox that is not checked, formdata will not collect it. You can...
Web - GWT Google

GWT is a Java-to-JavaScript compiler Java high-performance web applications without the developer having to be an expert in: browser quirks, XMLHttpRequest,...
Web - Server

A web server is a HTTP server that respond to HTTP request, generally returning a web page (HTML) (but it can serve any type of files). The request is handled: by native handlers (module) (if the server...



Share this page:
Follow us:
Task Runner