Understanding the concept of AJAX seems relatively easy, however, I am struggling to grasp the logic. While exploring how AJAX works, I came across the following example on w3schools.com, which is quite similar to examples on other sites as well.
<!DOCTYPE html>
<html>
<body>
<h2>Retrieve data from XML file</h2>
<p><b>Status:</b> <span id="A1"></span></p>
<p><b>Status text:</b> <span id="A2"></span></p>
<p><b>Response:</b> <span id="A3"></span></p>
<button onclick="loadDoc('note.xml')">Get XML data</button>
<script>
Upon clicking the button, the function is triggered.
function loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById('A1').innerHTML = xhttp.status;
document.getElementById('A2').innerHTML = xhttp.statusText;
The next step is to populate the A3 span with the server response. However, we have yet to determine the URL.
document.getElementById('A3').innerHTML = xhttp.responseText;
}
};
Now, we define the URL.
xhttp.open("GET", url, true);
Then, we send the request.
xhttp.send();
}
</script>
Finally, the result is displayed.
</body>
</html>
Surprisingly, the code works seamlessly. However, one interesting observation is that the div update occurs before setting the URL, meaning that the data from the server was not yet retrieved at that point.
This raised a question in my mind - how does the anonymous function (xhttp.onreadystatechange) interact with the xhttp.send() command? Does the onreadystatechange command continuously loop until the specified conditions are met?