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

ReactJS attempting to invoke a class function using a dynamically generated button

When attempting to access the deletePost(index) method from the ShowPost class using a dynamically rendered button within the render() step in React, I encounter an issue. The button labeled "click me" successfully retrieves and prints the first item in my ...

Utilizing Vue.js components and properties to invoke a function

Trying to create a shopping cart button that keeps track of how many times it's clicked, but encountering an issue where the function called by the button doesn't receive the correct parameter. I attempted using {{id}} and :onClick="addThisToCar ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

My code to hide the popup when clicking outside doesn't seem to be working. Can you help me figure out why?

After searching around on stackoverflow, I stumbled upon a solution that worked for me: jQuery(document).mouseup(function (e){ var container = jQuery(".quick-info"); if (container.has(e.target).length === 0) { container.hide(); } }); ...

Vue: setInterval not updating timer variable

Here is my code for updating and displaying the number of elapsed seconds: <template> <div> {{timerValue}} </div> </template> <script> export default { name: "App", components: { }, da ...

Different approach for searching and modifying nested arrays within objects

Here is an example of the object I am working with: { userId: 111, notes: [ { name: 'Collection1', categories: [ { name: 'Category1', notes: [ {data: 'This is the first note& ...

Experiencing issues with transferring JSON response from Axios to a data object causing errors

When I try to assign a JSON response to an empty data object to display search results, I encounter a typeerror: arr.slice is not a function error. However, if I directly add the JSON to the "schools" data object, the error does not occur. It seems like th ...

The Material UI Select Component has the ability to transform a controlled text input into an uncontrolled one

I encountered a warning in the console while trying to update the value of a Select input. The warning message is as follows: index.js:1446 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not swi ...

Store the token securely in your browser's localStorage and set up interceptors

Struggling with saving the token in localStorage and pushing it in interceptors to send it with all requests. Currently, passing user data and token from Symfony controller to frontend, but facing roadblocks in saving the token in localStorage and settin ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

Implementing an onclick event listener in combination with an AJAX API call

I'm really struggling with this issue. Here's the problem I'm facing: I have a text area, and I need to be able to click on a button to perform two tasks: Convert the address text into uppercase Loop through the data retrieved from an API ...

Styled-components is not recognizing the prop `isActive` on a DOM element in React

In my code, I have an svg component that accepts props like so: import React from 'react'; export default (props) => ( <svg {...props}> <path d="M11.5 16.45l6.364-6.364" fillRule="evenodd" /> </svg> ) ...

When new AJAX content is loaded, Isotope container fails to properly target the new objects and instead overlaps the existing ones

My webpage loads all content through an AJAX call. Initially, I tried placing my isotope initialization code inside a document ready function, but it didn't work as expected: $(function(){ container = $('#content'); contain ...

Creating a collaborative storage space within a MERN project folder

Currently, I am developing an application using the MERN stack. The structure of my project repository includes both backend and frontend components: my-project/ ├── backend/ │ │ │ . │ . │ └── package.json ├── fronten ...

Implementing event handling with .On() in Jquery following .Off()

I need assistance with my responsive navigation bar. I am having trouble with the jQuery code to disable hover events if the width is less than or equal to 768px and enable it for desktop screens. $(window).on('load resize', function (e) { v ...

Is it possible for a JWT generated using RS256 to be decoded on the jwt.io platform?

After setting up my first Express server and implementing user authentication with jwt, I'm now searching for a method to encrypt the jwt in order to prevent users from viewing the payload on the website. I am curious if anyone is aware of an encryp ...

Rails: Unable to manipulate the value of text_field using jquery

When a user selects an item from a list, I want to update the value of the item's codenumber field using jquery. Here is what my view looks like: <tr class="nested-fields"> <td style="width:180px"> <%= f.text_f ...

"Troubleshooting: Inability to send emails through PHP mail script while using jQuery's

I'm at a loss with this issue. I'm attempting to utilize the jQuery ajax function to send POST data to an email script. Below is the jQuery code snippet. $('#bas-submit-button').click(function () { var baslogo = $('input#bas- ...

In JavaScript, the input box is set to automatically capitalize the first letter, but users have the ability

How can I automatically capitalize the first letter of a user's name input, but allow for overrides like in the case of names such as "de Salis"? I've read on Stack Overflow that CSS alone cannot achieve this with text-transform:capitalize;, so ...

What is the best way to incorporate an npm module in a django-admin widget without the need to install node?

Background I am working on a Django app and need to create an admin widget. The widget will display text in a unique terminal-style format to show forwarded logs from an analytics process managed by Django (using the django-twined extension). To achieve ...