I'm using a vanila javascript class that sends request to other page. I want a loading spinner to come up to browser for waiting untill the send request ends.
Below is my code that calls the loading spinner before an XMLHttpRequest instance is being created. And remove the loading spinner after the XMLHttpRequest loading ends.
there is no error but I can't see the loading spinner on my browser... Can you tell me what I am missing?
class BYEPC_HTTPRequest {
constructor(uri, params) {
this.uri = uri;
this.params = params;
this.response;
this.loadingSpinner(); // I added loadingSpinner to document before XMLHttpRequest.
this.callQueryPage();
}
loadingSpinner() {
document.body.insertAdjacentHTML('beforeend',
`
<style>
.loader {
border: 16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid #3498db;
animation: spin 2s linear infinite;
z-Index: 100000;
position: fixed;
display: block;
boxShadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
width: 70px;
height: 70px;
top: 50%;
left: 50%;
top: 40%;
left: 40%;
transform: translate(-50%, -50%);
msTransform: translate(-50%, -50%);
webkitTransform: translate(-50%, -50%);
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<div id="loader" class="loader"></div>
`
);
}
callQueryPage() {
var httpRequest = new XMLHttpRequest();
httpRequest.onloadend = function(e) {
document.getElementById('loader').remove();
};
let _this = this;
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
_this.response = httpRequest.responseText;
}
else
{
alert("status : " + httpRequest.status);
}
}
}
httpRequest.open("POST", this.uri, false);
httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httpRequest.send(this.params);
}
sleep(delay) {
const delayUntil = Date.now() + delay;
while(Date.now() < delayUntil);
}
}
you have to bind the "progress" event on XMLHttpRequest and there you have to append the spinner.
for more detail refer https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#types_of_requests