Unusual JavaScript AJAX antics

I have a situation that looks like this:

elFinder.prototype.commands.info = function()
{
    this.exec = function(hashes)
    {
        var temp_array = new Array(),
            temp_html = new String();
        var request = new XMLHttpRequest();

        request.onload = function()
        {
            temp_html = "<a href='foo'>bar</a>";
            temp_array.push(temp_html);
            alert("Inner - Array size is " + temp_array.length); 
        }
        request.open("get", "example.com/url", true);
        request.send();
        alert("Inner - Array size is " + temp_array.length); 
    }
}

This results in the following outputs, respectively:

Inside - Array size is 1

and

Outside - Array size is 0

It appears that the array content is being somehow lost.

Answer №1

The issue lies within the AJAX concept itself. Specifically, setting true in the

request.open("get", "foo.com/url", true);

determines that the request should be handled asynchronously (by the way, it is recommended to use this mode in the main thread environment, as browsers like Chrome are moving away from synchronous requests due to their high latency).

This realization came after noticing the different order of the alert() messages when testing the code snippet in Firefox compared to Chrome.

In my specific scenario, I needed a synchronous behavior, so I changed the boolean flag to false.

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

Animating object on display and returning it with keyframes

Given the code snippet below: <div class="leftBox"> <div class="mainNode" ></div> </div> <script type="text/javascript"> $('.mainNode').click(function() { var element = $('.mainNode'); if (!ele ...

Having trouble identifying whether a file is a picture or video based solely on its extension

My current challenge involves determining whether an uploaded file is a video or a photo. This distinction is crucial as it dictates whether the file should be sent to my telegram bot as a video or photo attachment. Despite having what seems like a logica ...

Tips on retrieving the ID value

My goal is to access the value of the 'id' property in a component. Below is my attempt: constructor(props) { super(props); this.state = { ...

Initialize React Native project

Which ruby command shows the path to Ruby: /Users/User/.rbenv/shims/ruby Ruby -v command displays the version of Ruby installed: ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21] Which bundle command reveals the path to Bundler: /Users/Us ...

What is the best way to iterate through this JSON data and add it to a div in an HTML document?

Here is the structure of my JSON: { "content": [ { "title": "'I need some rest'", "description": "Descript One", "link": "http://www.google.com/?id=90#hhjjhjC-RSS", "guid": "http://www.google ...

Updating content in AngularJS based on the sidebar can be achieved by following these steps:

Yesterday, I posed a question about how to implement multiple views with Angular in order to have a header and sidebar. After receiving some helpful insights, I was able to make progress on creating a header and sidebar for my AngularJS App. You can view ...

Navigating with React Router using URL parameters

After implementing react router with a route path taskSupport/:advertiserId that includes parameters, I encountered an issue when trying to access the link http://localhost:8080/taskSupport/advertiserId. My browser kept returning 404 (Not found) errors for ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

Tips for organizing a Material UI DataGrid table effectively while keeping the total sum rows within the DataGrid unaffected

Check out my codeSandbox link here: https://codesandbox.io/s/making-sum-of-column-in-datagrid-mui-zjzfq6?file=/demo.js I've noticed that when I sort by ascending, the subtotal, total, and tax rows move up, but when I sort by descending, they move dow ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

Encountering issues with installing the "useHistory" hook in React

Currently working on a Google clone as a mini project and in need of importing useHistory from react-router-dom. My approach has been as follows: Step 1: Executed npm install --save react-router-dom (in the terminal) Step 2: Implemented import { useHisto ...

The load event in React's iframe is failing to fire after the src attribute is modified using state

In the process of creating a registration form for a React application, we encountered the need to incorporate an HTML legal agreement as an iframe. This legal document is available in various languages, one of which can be selected using a drop-down menu; ...

The jssor slider cannot be initialized when it is loaded through ajax requests

Incorporating jQuery's .load() function, my website dynamically loads the HTML code for the jssor slider. To verify the functionality of my code, I have developed a duplicate page which already includes the necessary slider code without utilizing an a ...

Mongo slices left blank

I'm currently working on an image upload feature using MongoDB, nodeJS, express, multer, jimp, and gridFS. Initially, I upload the image with multer, then resize it with jimp before uploading the jimp buffer to MongoDB. However, when I try to delete t ...

Guide to validating a Chinese mobile phone number using regular expressions

I need help validating a Chinese phone number that must begin with the number 1 followed by 10 additional numbers, for example: 14375847232 Any assistance would be appreciated. Thank you. ...

Alter the database field value in MongoDB without relying on req.body inputs

Is there a way to update a value from X post in my database without using a form in my front end app? I need to trigger the update through a button click instead. Typically, we use req.body to send data from a form. But how do I handle updating the value ...

What is the best way to pass a value from an addEventListener to another object for use?

In my project, I am trying to create three sliders that can adjust the color of a div when changed. Each slider functions properly, and I am able to track the value changes in the console. However, I am facing a challenge when attempting to assign that val ...

Type of element returned

Is there a way to retrieve the element type? I'm interested in applying the style of a class to HTML5 elements without using the class attribute. <!DOCTYPE> <html> <head> <title>My page</title> </head& ...

``What is the best way to include a JavaScript jQuery variable value within a PHP array

Let's consider the following scenario: var folderName = jQuery.trim($('#dirname').val()); var parentFolder = jQuery.trim($('#parent').val()); var dynamicUrl = '<?=$this->url(array('controller'=>'index ...

Error: Unable to load L.GeometryField constructor in django-leaflet library

I'm having trouble saving a geolocation to a Postgres database using Django-leaflet. I keep getting an error message that says Uncaught TypeError: L.GeometryField is not a constructor. My code involves AJAX calls. <script> var csrftoke ...