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.
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. |
With a get request
function onLoaded() {
var data = JSON.parse(this.responseText);
data.items.map(item => (
console.log(item.name+" "+item.price)
));
}
function error(err) {
console.log('Fetch Error', err);
}
var xhRequest= new XMLHttpRequest();
xhRequest.onload = onLoaded;
xhRequest.onerror = error;
xhRequest.open('get', '/doc/json/items.json', true);
xhRequest.send();
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);
}
}
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+")");
}
}
}
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"} }');
In the Browser devtool, you can see the request.
Example with Chrome.
You can see the type of request with the X-Requested-With header.
X-Requested-With:XMLHttpRequest
In the send method, you are passing the body.
If you pass:
Note that that you can overwrite the mime (content-type)