Share via:

JavaScript HTTP Client Class

Simple class to perform HTTP Request in plain JavaScript.

144 views

Edited: 2019-10-13 06:10

This is a very simple JavaScript class to send HTTP requests using AJAX techniques, as used here on Beamtic (as of 2019).

It works for both GET and POST request. I have not yet implemented other types, such as the HEAD request type.

The class can be used without restrictions in your own code. Keep an eye on Beamtic's GitHub page for an updated version.

The class can be used like this:

httpClient = new http_client();

httpClient.get("/request_handler.php", callback);

function callback(response) {
  // Do stuff here
  alert(response);
}

JavaScript HTTP Client:

class http_client {
    constructor() {
        this.response = false;
    }
    post(URL = 'required', postData = false, callBack = false) {
        this.newXMLHttp(callBack);
        this.xmlhttp.open('POST', URL, true);
        this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        this.xmlhttp.send(postData);
    };
    get(URL = 'required', callBack = false) {
        this.newXMLHttp(callBack);
        this.xmlhttp.open('GET', URL, true);
        this.xmlhttp.send();
    };
    newXMLHttp(callBack) {
        this.xmlhttp = new XMLHttpRequest();
        this.xmlhttp.onreadystatechange = () => {
            if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
                this.shouldWeCallBack(callBack);
            }
        };
    }
    shouldWeCallBack(callBack) {
        // Sometimes we may need to return the response body
        // Also note that many situations are best handled on the server-side,
        // in which case we may rely on the response to tell a user what went wrong.
        if (callBack !== false) {
            // The callBack function contains the actions to perform after loading the response
            // It is passed to the get() method from the calling block
            callBack(this.xmlhttp.responseText);

        } else {
            return true; // If not returning the response, return true
        }
    }
}

Comments