Share via:

JavaScript HTTP Client Class

Simple class to perform HTTP Request in plain JavaScript.


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

JavaScript HTTP Client:

class http_client {
    constructor() {
        this.response = false;
    post(URL = 'required', postData = false, callBack = false) {
        this.newXMLHttp(callBack);'POST', URL, true);
        this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    get(URL = 'required', callBack = false) {
        this.newXMLHttp(callBack);'GET', URL, true);
    newXMLHttp(callBack) {
        this.xmlhttp = new XMLHttpRequest();
        this.xmlhttp.onreadystatechange = () => {
            if (this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
    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

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