LifePex/public/js/ajax.js
Arthur Poulet f6a951f704
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
userpex: improve error and fix test databases
2021-06-24 22:10:58 +02:00

35 lines
852 B
JavaScript

async function ajax({
method = "GET",
url = ".",
body = undefined,
headers = {},
on_success = () => {},
on_failure = () => {},
}) {
const xhttp = new XMLHttpRequest();
const return_on_sent = new Promise((resolve, reject) => {
try {
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4) {
const response_status = String(xhttp.status);
if (/2\d\d/.test(response_status)) {
resolve(on_success(xhttp.responseText, xhttp));
} else {
resolve(on_failure(xhttp.responseText, xhttp));
}
}
};
} catch (err) {
reject(err);
}
});
xhttp.open(method, url, true);
Object.keys(headers).forEach((header_key) => {
xhttp.setRequestHeader(header_key, headers[header_key]);
});
xhttp.send(body);
return return_on_sent;
}