I have a page where the user can click a button to retrieve data via an xhr get request. While the data is loading and being parsed, I want a loading message to be displayed, which will be replaced with the data once it is ready. I'm using dojo libraries, so would rather not include jQuery or other libraries.
This is a simplified version of the set up I'm using:
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
// Bind function to click me div
var clickMe = document.getElementById('clickMe');
clickMe.addEventListener('click', getResults, false);
function getResults () {
// Display the loading message while results are retrieved
var resultsDiv = document.getElementById('results');
resultsDiv.classList.remove('hidden');
// Get the data and parse it here using a standard dojo.xhrGet method
var displayResults = getData();
// Output data to resultsDiv, overwriting loading message
resultsDiv.innerHTML = displayResults;
}
The problem I'm having is that the getResults function always waits until the getData function has completed before removing the 'hidden' class and showing the results div. This means that the user never sees the loading message, only the retrieved data, even if there's a delay while the data is processed. However, if I put an alert in the middle the function is forced to pause, the loading message is displayed:
function getResults () {
// Display the loading message while results are retrieved
var resultsDiv = document.getElementById('results');
resultsDiv.classList.remove('hidden');
// The loading message will be displayed if this alert is included
alert ("Hello world!");
// Get the data and parse it here using a standard dojo.xhrGet method
var displayResults = getData();
// Output data to resultsDiv, overwriting loading message
resultsDiv.innerHTML = displayResults;
}
I have tried replacing the alert with console.log, but it reverts to not showing the loading message. I've also tried setting up getting the data as a callback function inside displaying the loading message, but again it doesn't show anything. I have also tried with the get request set to sync: true as well as sync: false, but again no luck.
How can I make sure the loading message is displayed while waiting for getData?
Edit:
This is the getData function. I have tried both with and without syncing.
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;
}