I want to keep my website still on loading state while the ajax is still getting the response, and then when the ajax is successful, the website should stop loading.
'still on loading progress' means your browser's tab progress bar symbol remains visible and spinning, indicating that the website is still loading.
Please help me out, I'm out of ideas. This is definitely a beginner question with various solutions.
The HTML file's source code is found below:
<!DOCTYPE html>
<html>
<body>
<pre id="response">This will be the response...</pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
try {
$.ajax({
'url': 'https://example.com',
'type': 'GET',
'success': function (data) {
//I want to only finish loading the page after this is executed
document.getElementById("response").textContent = data;
} });
} catch(err) {
document.getElementById("response").textContent = err.message;
}
</script>
</body>
</html>
The thing that happens with my current code above is my website finishes on loading already (no visible spinning symbol in the tab already) even if the success function in ajax is still not executed or in other words, still awaiting response from ajax.
Thank you in advance for answering my question : )
CodePudding user response:
AJAX calls are asynchronous so they cannot block the webpage from loading from the browser's perspective. The browser will stop showing the "loading" symbol in the tab once it has reached the end of your HTML/JS scripts, which in your code it will due to asynchronous AJAX.
Some quick Googling has led me to this documentation on settings you can pass to jQuery AJAX: https://api.jquery.com/jQuery.ajax/. Which says AJAX has a setting for doing synchronous calls (async: false
). But I believe this is not really recommended as the point of AJAX and any REST call made from your frontend is to be asynchronous and not block the browser. But if this is your requirement this might work. :)