JavaScript HTTP Client Class
Simple class to perform HTTP Request in plain JavaScript.
1349 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: