The "truth" parameter within the xmlHttpRequest .open() function

After referencing MDN, it mentioned that by default, the JavaScript function will keep running until the server response is received.

This is essentially what AJAX is all about - Asynchronous JavaScript and XML.

Even though I have some experience with AJAX, I found myself a bit puzzled after reading that explanation. It made me question whether I truly understand the concept of AJAX. I do know that AJAX allows communication with the server without refreshing the page, meaning everything happens seamlessly in the background.

However, the scenario described in the reference got me thinking. For instance, if I have a piece of JavaScript code like this:

//true, hence the function runs while waiting for server response
var xmlResponse;
var url = "http://example.com/file.xml";
xml_req.open("GET", url, true); 

xml_req.onreadystatechange = function() {
     if(xml_req.readyState == 4 && xml_req.status == 200) {
        if(xml_req.responseText != null)
             xmlResponse = xml_req.responseXML; //server response may not yet arrive
        else {
             alert("failed");
             return false;
        }
     };
xml_req.send(null);

Based on this, it seems like xmlResponse could potentially be undefined since the server is still busy fetching the data. Can someone please clarify how the execution flow works in AJAX technology? Your insights are greatly appreciated.

Answer №1

If you want more details, check out my article here, but here's the gist of it.

When you set it to true, you're essentially making an asynchronous request. This means that the code won't pause while the http request is ongoing. On the other hand, a synchronous call will lock up the browser, preventing anything else from running, which can lead to issues. Asynchronous is preferred for this reason.

The XHR object keeps us informed about its activities, sending updates through the onreadystatechange event. By registering a function, we can monitor its progress, as this event occurs 4 times, each with a different state:

0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

We can access the data once the readystate reaches 4.

In the provided code snippet, it's checking for the complete state, ensuring that the status is 200 [ok]:

if(xml_req.readyState == 4 && xml_req.status == 200){

Attempting to use the xmlResponse value elsewhere in the code before it's returned will result in it being undefined. For instance:

ml_req.send(null);
alert(xmlResponse );

Check out one of the earliest articles on the XMLHttpRequest for further information. Here's a link to the Apple Article on xmlhttpreq.

Answer №2

It is crucial to realize that the onreadystatechange handler does not get executed immediately. In fact, it runs more than once. A better way to understand this concept is by breaking down the code into separate functions:

function initiateRequest(url)
{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = handleResponse;
    xhr.send();
}
function handleResponse(e)
{
    if (this.readyState == 4)
    {
        // Server response is fully received with xhr.readyState == 4
        if (this.status == 200)
        {
            // Response status is good with xhr.status == 200
            var response = this.responseXML;
            ...
        }
    }
}

Initially, the initiateRequest function is called and exits. Subsequently, when a response is received from the server, the handleResponse function is invoked. At each instance, we verify if the complete response has been received before proceeding with further processing.

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

Troubleshooting: Height setting issue with Kendo UI Grid during editing using Jquery

Issue: My Kendo UI JQuery Grid is fully functional except for a bug that occurs when adding a new record. When I add and save a new record, the grid's footer "floats" halfway up the grid and the scrollbar disappears, making it look distorted. Furth ...

What location is ideal for making API calls with React and Redux-thunk?

After extensively searching on StackOverflow.com and across the internet, I couldn't find a similar question. Therefore, please refrain from giving negative reputations if you happen to come across one as I truly need reputation at this point in my li ...

Enhanced JavaScript Regex for date and time matching with specific keywords, focusing on identifying days with missing first digit

I have a specific regular expression that I am using: https://regex101.com/r/fBq3Es/1 (audiência|sessão virtual)(?:.(?!audiência|sessão virtual|até))*([1-2][0-9]|3[0-1]|0?[1-9])\s*de\s*([^\s]+)\s*de\s*((19|20)?\d\d) ...

Using PHP and AJAX to implement pagination feature from a file

Looking to implement pagination in PHP using AJAX, where data is fetched from a file. When searching for a keyword, the page displays the first 20 records from the file. Now, I want to show the remaining records from the file with pagination. Any suggest ...

Error encountered while executing jest tests due to an unexpected import token

Despite trying numerous solutions and suggestions on Stack Overflow, I am still unable to resolve the issue at hand. I recently discovered jest and attempted to use it by following a tutorial on testing React components with jest from DZone. However, when ...

Error: The function scrollIntoView is invalid and cannot be found

I'm currently new to working with react-testing-library / jest and trying to create a test that checks if the route navigation (using react-router-dom) is functioning correctly. I've been following the guidance from the README as well as this hel ...

Searching for a MongoDB document using its unique identifier

Currently, I am working with Node.js and MongoDB where my database is hosted on MongoHQ (now compose.io). I have come to understand that document IDs are converted to hex strings, but I am struggling to retrieve a document using its ID. In my dataset, the ...

Raspberry Pi encountering a TypeError with Node.js async parallel: "task is not a function" error

I am new to nodejs, so I kindly ask for your understanding if my questions seem simple. I am attempting to use nodejs on a Raspberry Pi 3 to control two motors, and I keep encountering the error message "async task is not a function." Despite searching fo ...

Automatically close an element when you click on a different element

Hello everyone! I need some help again. I'm working on a script that displays an overlay when a menu item is clicked. Within this menu, there is a modal contact form with a close icon or anchor that should appear when clicked. My goal is to have the o ...

Exploring the world of Node.js callback parameter passing

Currently, I am diving into the world of Node callbacks and JavaScript in general. As I delve deeper, I find myself puzzled by the following snippet: var request = require('request'); request('http://www.google.com', function (error, ...

Tips for effectively utilizing the ajax() function within JQuery

Within my javascript file, the following code is present: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> $.ajax({ type: 'post&apo ...

The AJAX call in PHP is echoing JavaScript code that seems to be malfunctioning

Currently working on an AJAX page using php, where I plan to output a section of JS code upon completion. Despite having the JS code within the HTML page, it is not functioning properly. Any suggestions on how to get it to work? ...

Retrieve the ID of the nearest div without it being executed twice

I am currently working on implementing a close button using 'onclick' functionality. The goal is to hide the parent ID element when the user clicks the button, as shown below. function displayNone() { var id= $('.btnClose').closest ...

Utilizing JQuery's ajaxComplete method to handle all Ajax requests on the webpage

I am working with a Java Script file and I need to perform an action after each Ajax request/response is completed. However, since I have multiple Ajax requests/responses, I want the action to be triggered only after all of them are completed. $(document) ...

Exporting a variable to multiple files for use as a string property

My goal is to send a base URL to each file, which will be combined with the existing full path stored as a property in another object. However, I encounter an error message indicating an invalid URL when attempting to use the path. Here is the setup on th ...

Guide to transforming an embed/nested FormGroup into FormData

Presenting my Form Group: this.storeGroup = this.fb.group({ _user: [''], name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])], url_name: [''], desc: ['', Validators.compose([Valida ...

"In the most recent version of THREE.js (r82), the shadow is not detectable

I am having trouble casting a shadow from a cube onto a plane using MeshLambertMaterial in my code. Despite setting up the scene correctly, the shadows are not appearing as expected. Most solutions I have come across suggest that objects should be within ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

Ensure that the search input field is in focus whenever the showSearch state is true

Having difficulty focusing on the input field whenever the showSearch state is true. Utilizing useRef and useEffect for this purpose. When the showSearch flag changes, the useEffect hook is triggered to check if showSearch is true, and if so, it should foc ...

"Dealing with cross-origin resource sharing (CORS)

When calling an API using isomorphic-fetch and the Fetch API, I encountered a CORS issue because the API was hosted on a different domain (this worked fine in production). To work on development locally, I had to run Chrome browser in non-secure mode and ...