XHR – request without promises

Posted by

XHR (XMLHttpRequest) is one of the web APIs that allows browsers to interact with servers. Since the code with XHR does not look very clean, there are AJAX libraries such as jQuery.ajax() that work as a wrapper around XHR to simplify the code. Later, Fetch API – promise-based HTTP request was introduced and deprecated the use of XHR. However, JavaScript promise is part of ES6 which means Fetch API does not support legacy browsers such as Internet Explorer. So, in any case that server requests without promises are necessary, XHR is still the use case.

This article will explain how to use XHR:

  1. make a GET request
  2. make a POST request
  3. set request headers
  4. handle server responses
  5. prevent multiple requests at one time

How to make a GET request

XMLHttpRequest() is the constructor that initializes an XMLHttpRequest. xhr.open() is the method that initializes a newly-created request, or re-initializes an existing one. Finally, xhr.send() executes sending the request to the server.

var xhr = new XMLHttpRequest();

xhr.open('GET', url);

xhr.send();

How to make a POST request

When making a POST request, you will only need to change the method parameter and fill data in xhr.send().

var xhr = new XMLHTTPRequest();

xhr.open('POST', url);

xhr.send(data);

How to set request headers

xhr.setRequestHeader() allows setting headers on the request. The code below sets Content-Type to application/json.

XMLHttpRequest.setRequestHeader('Content-Type', 'application/json')

How to handle server responses

Instead of promises, XHR uses events that are fired when its request status changes. By setting callbacks to the specific request event handlers, you can manage to handle server responses.

/* event that fires when xhr request completes */
xhr.onload = function() {
    doSomething(xhr.response);
}

/* event that fires when xhr request ends with an error */
xhr.onerror = function() {
    handleError();
}

Prevent multiple requests at one time

By accessing xhr.readyState, it is possible to prevent more than one request at a time.

  • Cancel receiving response for the previous request if it has been opened but unsent.
  • Cancel sending the new request if the previous request has been already sent but the response is on hold

The code below is from my github repo.

const xhr = new XMLHttpRequest();

function sendHttpRequest = (method, url, data) => {
    if(xhr.readyState === 1) {
        // this cancels receiving response for the previous request
        xhr.abort();
        return ;
    }

    if(xhr.readyState > 0 && xhr.readyState < 4){
        /* after data is sent to the server */
        console.log('Current request aborted!');
        return ;
    }

    /* initializes a newly-created request, or re-initializes an existing one */
    xhr.open(method, url);

    xhr.send(JSON.stringify(data));
}

Thanks for reading.

Hope you enjoyed the article. If you have any question or opinion to share, feel free to write some comments.

Facebook Comments