Within the code below, I have attempted to demonstrate the execution flow of synchronous ajax requests. Two ajax requests are sent synchronously with a delay between them. The issue arises when only "Request 1" is displayed in the console, but the response text does not update in the DOM. It's only after the delay and completion of the second request that the first response text is finally shown, followed by the second response text.
The question arises as to why the first ajax response text takes longer to update in the DOM, even though the server-side response was received before the delay began?
index.html
-----------
<!DOCTYPE html>
<html>
<body>
<!--Calls the function synchronously(async=0/false) -->
<button type="button" onclick="loadDoc('ajax_info.txt')">Synchronous Operations</button>
<p id="result1"></p>
<p id="result2"></p>
</body>
<script type="text/javascript">
function loadDoc(url) {
console.log("Entered ");
ajax(1,url,"result1");
for(i=0;i<1000000000;i++){}
ajax(2,url,"result2");
console.log("Exit");
}
function ajax(requestNo, url, div) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(div).innerHTML = this.responseText;
console.log("Request " + requestNo);
}
};
xhttp.open("get", url, 0);
xhttp.send();
}
</script>
</html>
ajax_info.txt
--------------
This is the content from a txt file.