JavaScript HTTP Client Class

Simple class to perform HTTP Request in plain JavaScript.

1319 views

Edited: 2022-09-27 12:31

The HTTP client can be used to perform AJAX requests and update the page-content dynamically using GET and POST requests.

The class can be used like this:

httpClient = new http_client();

httpClient.get("/api/request-headers", function (response) {
  document.getElementById("_id_of_element").innerText = response;
});

When used on Beamtic, there is no need to instantiate the class, since it is loaded by the system automatically. Instead, authors may use it directly:

httpClient.get("/api/time/date", function (response) {
  document.getElementById("_id_of_element").innerText = response;
});

To use the HTTP client in articles here on Beamtic, you need only make use of HTML script elements in the article's code.

JavaScript HTTP Client

class http_client {
    post(URL = 'required', postData = false, callBack = false) {
    var http = new XMLHttpRequest();
    http.open('POST', URL, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    if ('string' == typeof postData) {
      http.send(postData);
    } else {
      if ('function' == typeof postData && false == callBack) {
        callBack = postData;
      }
      http.send();
    }
    this.ready(http, callBack);
  };
  get(URL = 'required', callBack = false) {
    var http = new XMLHttpRequest();
    http.open('GET', URL, true);
    http.send();
    this.ready(http, callBack);
  };
  ready(http, callBack) {
    http.onreadystatechange = () => {
      if (http.readyState == 4) { // && this.xmlhttp.status == 200
        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(http.responseText);
        } else {
          return true; // If not returning the response,
                       // return true
        }
      }
    };
  };
}

Tell us what you think:

  1. getElementById should be used to select unique elements in a HTML document. Selected elements can be manipulated with JavaScript.
  2. The Width and Height of the browser Window can be obtained through the innerWidth and innerHeight properties; these can be checked by an event handler to detect resize events.
  3. Cool tutorial on how to change the iframe src attribute value using JavaScript.
  4. You can either use a pure JavaScript solution, or you can choose to go with a library such as JQuery. Either way, this short tutorial show how it is done. Enjoy!
  5. In this Tutorial I am going to show how to create new elements in JavaScript, and how to add various types of content.

More in: DHTML