JavaScript - Simple AJAX HTTP web request for GET and POST
A simple asyncronous web script for sending HTTP requests.
// Helper function for Ajax calls
const webRequest = async function(url, opt) {
let _XmlHttp;
if (window.XMLHttpRequest) {
// code for modern browsers
_XmlHttp = function() {
return new XMLHttpRequest();
};
} else {
// code for old IE browsers
_XmlHttp = function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
const options = opt ? opt : {};
const headers = options.headers ? options.headers : {};
return await new Promise(function(resolve, reject) {
const xmlHttp = new _XmlHttp();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status === 0) {
reject(new Error("Request not sent by browser."));
}
resolve(this);
}
};
if (typeof options.timeout == "number") {
xmlHttp.timeout = options.timeout;
}
xmlHttp.withCredentials = typeof options.withCredentials == "boolean" ? options.withCredentials : false;
xmlHttp.open(options.method ? options.method : "GET", url, true);
for (const header in headers) {
xmlHttp.setRequestHeader(header, headers[header]);
}
xmlHttp.send(options.body ? options.body : "");
});
};
Simple use within an async
function.
(async function() {
const res = await sendRequest("https://example.com");
console.log(res.responseText);
})();
More options.
(async function() {
const res = await sendRequest("https://example.com", {
headers: {
Key: "Value"
},
method: "POST",
body: "Some payload"
});
console.log(res.responseText);
})();