JavaScript XMLHttpRequest (XHR): Part 1
Published: 2022-10-04 15:57:47

User experience is an important factor to put into consideration when building a project. There are so many subtle ways to improve user experience, and minimizing the level of disruption users experience while on a web page is one of them. For example, picture a scenario where a web page must frequently retrieve a particular piece of data from the servers; it would be annoying to the user if the web page does a full page refresh every time it retrieves that data. A way to avoid that is by issuing an XMLHttpRequest. Doing this enables a web page to update just part of a page without unnecessarily interrupting the user. In addition, XMLHttpRequest objects allow data retrieval from a URL without doing a full page refresh. This is because XMLHttpRequest objects are used to interact with servers. 
Despite its name, XMLHttpRequest isn't limited to just retrieving XML; it can be utilized to retrieve any type of data.

##Constructor

`XMLHttpRequest()`

This constructor is used to initialize an XMLHttpRequest and must be called before any other method calls.  

```javascript
new XMLHttpRequest();
```

##Methods
The following Methods have been made available for the XMLHttpRequest object;

####XMLHttpRequest.open()

This initializes a new request or re-initializes an already existing request. The syntax to use this method is written below;

`open(method, URL)
Open(method, URL, async)
Open(method, URL, async, user)
Open(method, URL, async, user, password)`

#####About parameters

Method: 
This is the HTTP request method to use, such as “GET”, “POST”, “PUT”, “DELETE”, etc. It can be ignored for none HTTP(S) URLs.

URL: 
A string representing the URL where the request is to be sent.

Async: 
An optional Boolean parameter is set to true by default. It indicates whether or not to run the operation asynchronously. When the value is set to true, a notification of a completed transaction is provided using event listeners. If false, the send() method doesn’t return until the response is received.

User: 
An optional parameter, it's a username used for authentication; by default, this has a null value.

Password: 
An optional parameter, it is a password used for the purpose of authentication. By default, this has a null value.

```javascript

const xhr = new XMLHttpRequest();
const method = “GET”
const url = “mypage.html”

Xhr.open(method, url, true);
```
####XMLHttpRequest.send()

This method is used to send the request to the server. For an asynchronous request, this method immediately returns the request is shipped, and its result is delivered using events. For a synchronous request, the method doesn't return until the response has arrived. The syntax to use this method is written below;

`send()
send(body)
`
#####About parameters

Body: 
An optional parameter sent in the XHR request that specifies the request's body, it's mainly used if request method is "GET” or “HEAD”. This can be 

•A document, in this case, serialization, is done before being sent.
•An XMLHttpRequestInit, which could be a blob, an array buffer, a typed array, a data view, a form data, a URLSearchParams, a string literal or an object as per the Fetch specs.
•Or null(used by default if no value is specified).

On a side note, the best way to send binary content is using a blob, typed array or data view combined with the send() method.

#####GET request

```javascript

const xhr = new XMLHttpRequest();
xhr.open(“GET”,”/webserver”, true);

xhr.onload = () => 
{
  // Request finished. Do processing here.
};

xhr.send(“string literal”);
// xhr.send(document);
// xhr.send(null)
```

#####POST request

```javascript

const xhr = new XMLHttpRequest();
xhr.open("POST", “/webserver”, true);

//Send the correct header information with the request
xhr.setRequestHeader("Content-Type", "application/x-www-dummy-file");

xhr.onreadystatechange = () =>

 { // Call a function when the state changes.
  
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) 
   {
    // Request finished. Do processing here.
    }
}

xhr.send("lasgidi==loreunknown");
// xhr.send(new Int8Array());
// xhr.send(document);
```

####XMLHttpRequest.abort()

This method aborts an already sent request. When a request is aborted, its ready state changes to XMLHttpRequest.UNSENT(0), and the request's status code is set to zero. The method syntax is written below;

`abort()`

Example code illustrating the abort() method in use 

```javascript

const xhr = new XMLHttpRequest();
const method = "GET";
const url = "https://www.google.com/docs/";

xhr.open(method, url, true);

xhr.send(“string”);

if (CANCEL_NOW)
{
   xhr.abort();
}

```
####XMLHttpRequest.getResponseHeader()

Returns a string containing a particular header's text value. In a scenario where multiple headers have the same name, their values are returned as a single concatenated string, where values are separated from each other by a pair of commas and spaces. The getResponseHeader() method returns  a UTF byte sequence as its value.   

`getResponseHeader(headerName)`

#####About parameters

headerName:
This is a string indicating the name of the desired header to return its text value. If the header is non-existent or hasn’t been received, it returns null.

Let's have an example where a request is created and sent, and a readystatechange handler is established to look for readyState to show whether the headers were received. In this case, the value of the Content-Type header is fetched. If the Content-Type isn't the desired value, the XMLHttpRequest is cancelled by calling abort()

This code illustrates the use of the getResponseHeader() method;

```javascript

const xhr = new XMLHttpRquest();
xhr.open(“GET”, “dummypage.html”, true);

xhr.send();

xhr.onreadystatchange = () =>
{
   If(xhr.readyState === xhr.HEADER_RECEIVED)
    {
        const contentType = xhr.getResponseHeader(“Content-Type”);  
        If(contentType !== my_expected_type)
          {
              xhr.abort();
          }
    }
}

```
####XMLHttpRequest.getAllResponseHeaders()

Returns a string containing all the response headers separated by CRLF or returns null if no response has been received. If a network error occurs, an empty string is returned.

`getAllResponseHeaders()`

This codeblock illustrates the use of the getAllResponseHeader() method;

```javascript

const xhr = new XMLHttpRequest();
const allResponseHeaders = xhr.getAllResponseHeaders();  

if (!allResponseHeaders)
   {   
      return false;  
   } 
else
   {
      const headers = allResponseHeaders.split("\r\n");  
      const headerNames = [];  
      for (var i = 0; i < headers.length; i++) 
          {   
              headerNames[i] = headers[i].split(":")[0].toLowerCase(); 
              console.log(headerNames); 
          }  
    }

```
####XMLHttpRequest.setRequestHeader()

This method is used to set the value of an HTTP request header. When using this method, the open() method must be called first, and then the send() method can be called after the setRequestHeader method call. In the case where this method is being called multiple times with the same header, the values are simply merged together in one single request header.

Each time a setRequestHeader() method call is initiated, after the first call, the specified text is affixed to the end of the existing header’s content.

`setRequestHeader(header, value)`

#####About parameters

Header:
Name of the header whose values are set.

Value:
The value is set as the body of the header.

This code block illustrates the use of the setRequestHeader() method to delete a file created at a random date;

```javascript

const request = new XMLHttpRequest();
localStorage.token = localStorage.token || (Date.now()*Math.random);

deleteJSON(“application/json”, call);

const call = callBack();

Function callBack() 
{
    document.getElementById("demo").innerHTML = this.responseText
}

function deleteJSON(url, cb)
{
    request.onload = cb;
    request.open(“DELETE”, url);
    request.setRequestHeader(“authorization”, localStorage.key)
    Request.send();
}


```
####XMLHttpRequest.overrideMimeType()

This method is used to override the MIME type provided by the server.

overrideMimeType(mimeType)

#####About parameters

mimeType:
A string thats overrides the MIME type used instead of the server-specified one. If a type is unspecified, XMLHttpRequest assumes "text/XML". 

```javascript

//this code interprets the received data as plain text
request = new XMLHttpRequest();
request.overrideMimeType("text/plain");
request.addEventListener("load", callback, false);
request.open("GET", URL);
request.send();
```