Exploring the mechanics of an Ajax call

Feeling a little lost in the call flow of Ajax - can anyone provide some guidance?

This is my HTML:

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>

My JavaScript:

var xmlhttp;

function loadXMLDoc(url, cfunc) {
    alert("4");
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    alert("5");
    xmlhttp.onreadystatechange = cfunc;
    alert("6");
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

function myFunction() {
    alert("1");
    loadXMLDoc("ajax_info.txt", function() {
        alert("2");
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert("3");
            document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
        }
    });
}​

From what I understand, the Alert box sequence should be

1 2 3 4 5 6

However, it actually appears as

1456222223

Could someone please clarify why the function is being called first? I thought the function couldn't be executed until the parameter values were ready.

Answer №1

executeLoadXMLDoc(...) is a function that runs immediately upon being called.
The callback passed to it (which contains alert("2")) will only be executed when triggered by an event, specifically when the XMLHTTPRequest triggers onreadystatechanged.

The onreadystatechanged event can fire multiple times for various state changes, as indicated by the readyState property.

Answer №2

Once the initial alert is fired, the function loadXMLDoc is immediately called and passed an anonymous function containing alerts "2" and "3". It's important to note that this function isn't executed at that moment - only a reference to it is passed so that loadXMLDoc can execute it later.

That's why you initially see "1 4 5 6" as output.

xmlhttp.onreadystatechange = cfunc;
assigns the anonymous function we passed to loadXMLDoc as the onreadystatechange handler. This event is triggered multiple times during an AJAX request whenever the browser detects a change in the request state (it's worth noting that the readyState value may not change every time).

This explains why "2" is displayed multiple times.

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    alert("3");
    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}

Within the onreadystatechange handler, there's a check for the readyState being equal to 4 and the status being 200. A readyState of 4 indicates that the request has been completed, while the comparison with status == 200 verifies the success of the HTTP response.

Therefore, "3" is only displayed last because it's executed once the request is finished, meeting the conditions outlined in the if statement.

For further insights, consider reading the MDC article on making AJAX Requests.

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

Instantly display selected image

I have encountered some challenges with my previous question on Stack Overflow as I couldn't find a suitable solution. Therefore, I decided to explore an alternative method for uploading images. My current goal is to upload an image immediately after ...

Firebase ref.on('value') will repeatedly trigger, even if no changes have occurred

My current setup involves using an event listener to monitor changes in my real-time database. const [chats, setChats] = useState({}); const ref = db.ref(`users/${sender}/chat/`); ref.on('value', (snapshot) => { const data = snapshot ...

Having trouble determining the total amount in my online shopping cart

I am facing an issue with the shopping cart I created, which consists of two components (Productlist and Cart List). When I click on the 'add to cart' button in the Product List, it successfully moves into the service file and then to the Cart Li ...

The process of altering a span label's class with JavaScript

I am currently working with an HTML element that looks like this: <dd><span class="label label-success" id="status">Production</span></dd> My goal is to update it to: <dd><span class="label label-warning" id="status"> ...

How can we bring in prop array values in React?

I've been working on developing a small music player program in React. Is there a way to import all these values together with a single import statement? I noticed that manually inputting the values into the props array doesn't work because the ...

adjustable canvas dimensions determined by chosen images

I would like to create a canvas image based on the selected image <canvas id="canvas" ></canvas> <input type="file" id="file-input"> Using JavaScript: $(function() { $('#file-input').change(function(e) { var file ...

Modifying the information depending on the option chosen from the dropdown menu using angularJS

I have a dropdown menu where I can choose between two options, and when selected, the corresponding data is displayed. However, I would like to display the data that is inside a div tag instead. Check out this Fiddle Demo HTML: <div ng-controller="Ct ...

In order to use DIV jQuery, it is necessary to have at least one input

In my form, there are 5 input fields. On button click using JQuery, I need to validate that at least one of these inputs is filled out. <div id='myForm'> <input name="baz" type="text" /> <input name="bat" type="text" /> ...

Turning a string array into a basic array can be achieved through a few simple steps

While I am aware that this question has been posed multiple times, my scenario is slightly unique. Despite exhausting numerous methods, I have yet to discover a suitable workaround. $array = ["9","8","7","6","5"]; //result of javascript JSON.stringify() ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

"The issue of Django showing a 'select a valid choice' error when trying to populate a select field

I encountered a validation error while trying to create a form with an empty select field: area_sp = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control', 'id':'area_select'})) After populating the ...

Adding ngrx action class to reducer registration

Looking to transition my ngrx actions from createAction to a class-based approach, but encountering an error in the declaration of the action within the associated reducer: export enum ActionTypes { LOAD_PRODUCTS_FROM_API = '[Products] Load Products ...

Utilize conditional styling in Vue using CSS

I am having difficulty implementing a conditional Vue statement to change the CSS style based on the text value. Despite trying other tutorials, I have had no success due to my limited experience with Vue. For example, if I want the class to be "is-succes ...

Managing multiple sets of data in a structured form similar to an array

How Do I Send Form Data as an Array? Take a look at the code snippet below. I'm having trouble setting the index in product_attribute['index must be here']['key'] <tr v-for="index in attributes"> <td class="text-left ...

Having trouble with sending a JSON post request in Flask?

I have a setup where I am utilizing React to send form data to a Flask backend in JSON format. Here is an example of the code: add_new_user(e){ e.preventDefault() var user_details = {} user_details['fname'] = this.state.first_name user_d ...

Dynamically load WordPress content using ajax and incorporate CSS3 animations for added visual appeal

It's time for a new challenge to push my learning curve. I've never ventured into the world of ajax before, but it seems like a skill I need to acquire. What better opportunity to learn than by implementing it on a fresh portfolio site. The main ...

Adjusting the size of Bootstrap alerts while ensuring the close icon remains correctly positioned

Below is the HTML code snippet I am working with: <div class="row mt-2"> <div class="col-lg-5"> <div id="alertmessages"></div> </div> <div class="col-lg-7"> <div class="btn-group-sm"> ...

Steps to resolve the issue: The current experimental syntax 'classProperties' is not supported

I encountered an issue where the experimental syntax 'classProperties' is not supported when trying to run my react js application. My goal is to increment the value inside a <span> when a ` button is clicked. Below is the excerpt of my c ...

What is the best way to conceal text that is not enclosed in <p> or <span> tags?

I need to hide a specific portion of text in an HTML code snippet, however, the text is not wrapped in any specific element. Here is an example: <div class="content"> Give comfortable and durable place to work with a desk. Lock the center d ...