On my webpage, I have implemented a feature where users can click a button to fetch data using an xhr get request. During the loading and parsing of this data, I want to display a loading message that will be replaced with the actual data once it is ready. I am using Dojo libraries and prefer not to include jQuery or any other external libraries.
Here is a simplified version of how I have set it up:
HTML
<div id = "clickMe"> Click Me! </div>
<div id = "results" class = "hidden">
Please wait while we retrieve the results
</div>
CSS
.hidden {display: none;}
Javascript
// Attach function to click me div
var clickMe = document.getElementById('clickMe');
clickMe.addEventListener('click', getResults, false);
function getResults () {
// Display the loading message while results are being fetched
var resultsDiv = document.getElementById('results');
resultsDiv.classList.remove('hidden');
// Fetch and parse the data using a standard dojo.xhrGet method
var displayResults = getData();
// Show the fetched data in resultsDiv, replacing the loading message
resultsDiv.innerHTML = displayResults;
}
The issue I am facing is that the getResults function waits for the getData function to complete before removing the 'hidden' class and displaying the results div. This results in the user skipping the loading message and directly seeing the data, even if there is a delay in data processing. Interestingly, if I introduce an alert in the middle, it forces the function to pause and the loading message is shown:
function getResults () {
// Display the loading message while results are being fetched
var resultsDiv = document.getElementById('results');
resultsDiv.classList.remove('hidden');
// The loading message is displayed when this alert is included
alert("Hello world!");
// Fetch and parse the data using a standard dojo.xhrGet method
var displayResults = getData();
// Show the fetched data in resultsDiv, replacing the loading message
resultsDiv.innerHTML = displayResults;
}
I have tried replacing the alert with console.log, but the loading message does not show up. I also attempted setting up the data fetching as a callback function within displaying the loading message, but that did not work either. Even when using the get request with sync: true or sync: false, the loading message is not displayed.
How can I ensure that the loading message is visible while waiting for the getData function?
Edit:
Here is the getData function. I have tried both with and without sync:
function getData() {
var targetUrl = //some url;
var restResponse;
dojo.xhrGet({
url: targetUrl,
sync: true; // no difference when this is omitted
load: function(result) {
restResponse = result;
}
});
// Parse the rest response - fairly long function so I won't paste it here
var parsedResponse = parseResult(restResponse);
return parsedResponse;
}