Process
- Start by showing a loading indicator while waiting for the response from your service.
- Hide the loading indicator once the service has provided a response.
Steps to Follow
Here is how you can update your function:
function Post() {
// Step 1: Display the loading indicator
document.getElementById("loading-overlay").style.display = "block";
// Step 2: Create XHR instance
// ...
// Step 3: Response handling
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('new_story_post').innerHTML = xhr.responseText;
}
// Hide the loading indicator regardless of the response
document.getElementById("loading-overlay").style.display = "none";
}
}
// ...
}
Include the loading indicator in the body
:
<div id="loading-overlay">Loading...</div>
Add some styling with CSS:
#loading-overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 999;
text-align: center;
display: none;
}
Additional Tip
You might consider using a callback function for better code organization and flexibility.
function Post(textid, fn) {
// Step 1: Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} else {
return fn(new Error("Ajax is not supported by this browser"));
}
// Step 1: Create XHR instance - End
// Step 2: Define response handling - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200) {
fn(null, xhr.responseText);
} else {
fn(new Error('Request failed'));
}
}
};
// Step 3: Specify action, location, and send data to server - Start
xhr.open('POST', 'post.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("textid=" + textid);
// Step 3: Specify action, location, and send data to server - End
}
Usage example:
// Show loading indicator
document.getElementById("loading-overlay").style.display = "block";
// Obtain textid value
var textid = document.getElementById("textid").value;
// Call the Post function
Post(textid, function(err, res) {
if (err) {
// Handle errors
} else {
// Hide loading indicator
document.getElementById("loading-overlay").style.display = "none";
// Update the view
document.getElementById('new_story_post').innerHTML = res;
}
});