Having difficulty understanding the sequence of the JavaScript AJAX demonstration

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?

Answer №1

Insights on the onreadystatechange Property

The

XMLHttpRequest.onreadystatechange
property houses the event handler that gets triggered whenever the readystatechange event occurs. This event is triggered whenever the readyState property of the XMLHttpRequest object changes. The callback is executed on the user interface thread.

It's important to note that the readystatechange event won't be triggered if an XMLHttpRequest request is aborted using the abort() method.

The event doesn't continuously loop; rather, it gets triggered when the readyState value changes. The readyState can have values of 0, 1, 2, 3, or 4. The state of 0 indicates that open() hasn't been called yet. It's safe to set the readyState before calling open, and the order doesn't matter.

Answer №2

The execution of the function is triggered only when the browser calls the onreadystatechange method. The specific URL used to define the function does not affect this process.

  1. Upon a change in the "ready state" of the Ajax request, the assigned anonymous function is executed.
  2. The anonymous function then evaluates the current state of the request.
  3. If the request is completed and returns an HTTP status of OK, the DOM element is updated with the response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to automatically update the latest ID in one tab or window when inserting records in a separate tab or window?

I currently have a setup where one file, list-display.php, displays the latest ID. <div class="result"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <script> function refresh ...

tips for passing a string array to an actionresult

I've been struggling with a variable that is a string[] parameter. Despite my attempts to push values in the actionresult, I haven't been able to successfully match the string[] parameter. Here's what my ajax code looks like: var panels ...

What is the process for converting an array of objects into an array of form groups?

I am looking to utilize the array function of the formbuilder to handle formcontrol arrays. I have a custom object array that I need to integrate into a FormArray, but it seems to only accept FormGroup as arguments. How can I convert my array of custom obj ...

Can state be controlled by both the parent and children within the same element?

I am facing a situation where I have a component that requires updating the value from its parent, but also needs to handle user input changes without having to pass them back to the parent. See this scenario in action with this example: https://codesandbo ...

Issues with the PhoneGap app's InAppBrowser functionality

I've been working tirelessly on this project for several days, but have hit a roadblock and need some assistance. My goal is to open a PDF file sourced from a Dropbox account using JavaScript. The code works perfectly fine when uploaded through PhoneG ...

Tips for incorporating a Survey Monkey website embed into an Angular application

I have a Survey Monkey account with multiple surveys. I am trying to embed a survey from this website into my Angular website, which already has Bootstrap and jQuery added. I attempted to directly add the script in an HTML component, but it did not work. ...

Angular binding causing decimal inaccuracies

Within my $scope, I have a variable tobing that can be either 2.00 or 2.20, and I am binding it to: <span>{{datasource.tobind}}</span> I want the displayed text to always show "2.00" or "2.20" with the two last digits, but Angular seems to au ...

Prefering `window.jQuery` over the yarn version

I am currently in the process of transitioning to Vite 3 with Vite Ruby on Rails from Webpacker and Webpack. One major issue I have encountered is that my system functions as a CMS. Some of our long-standing clients have jQuery code embedded directly withi ...

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

"Upon clicking the commandButton with the bootsfaces iconAwesome, an Uncaught TypeError is triggered due to the inability to read the 'id' property

Whenever I click on a b:commandButton with an iconAwesome, the following error occurs: bsf.js.xhtml?ln=bsf:7 Uncaught TypeError: Cannot read property 'id' of nullBsF.ajax.onevent @ bsf.js.xhtml?ln=bsfsendEvent @ jsf.js.xhtml?ln=javax.faces:1 ...

Exploring the ID search feature in JavaScript

I'm facing an issue with implementing a search feature in my project. Here is the HTML snippet: HTML: <input type="text" id="search"> <video src="smth.mp4" id="firstvid"> <video src="smth2.m ...

Firebase authentication encountered an error due to a network request failure

Utilizing firebase Hosting to host my website, I am encountering a persistent error when attempting to login using email/password. This is the JavaScript code that I am using: window.onload = () => initApp(); //Initialize screen function initApp(){ ...

The Material UI autocomplete unexpectedly closes on click instead of displaying a popover as intended

I'm facing a challenge with adding a button to the Material UI autocomplete using the renderOption prop. I added a button to each row that was intended to display a PopOver component, but when clicking on the button, it automatically closes the autoco ...

Initiating a Page with Dynamic Modal Window according to Backend Exigencies

Dear experts, can you help me with a problem? I want to implement a modal window on an vb.aspx page if a specific condition from the codebehind query is true. How can I achieve this? Thank you! ...

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...

Modify the URL query to read as "favicon.ico"

Whenever I make a GET request to my node.js/express web server with a URL following the route, instead of storing that URL, the server ends up saving favicon.ico: var express = require("express"); var app = express(); app.get("/:query", function (req, re ...

Click on the image to view in a separate window

I am looking for assistance with a script that can open an image in a new page, not a new window. I have a specific HTML page designated for displaying various images when clicked on. If anyone has any ideas or guidance on how to achieve this, it would be ...

Mysterious data organization - transform into an object

As I interact with an API, there is a value that I cannot quite pinpoint. My goal is to transform this string into a JavaScript object, but the process seems complex and confusing. Does anyone have insight on what this data represents and how it can be co ...

Customizing multi select in MUIv5 AutoComplete feature

My current challenge involves using the mui Autocomplete multi-select component. I'm having trouble getting it to function according to my specific requirements. Essentially, I need to set default selected values passed as props from the Parent compon ...

What is the best way to access external value in an Angular directive?

check out this plunker link. HTML: <body ng-app="app"> <h1>selectable</h1> <selectable text="link1" status="true"></selectable> <selectable text="link2" status="false"></selectable> <p> ...