Numerous XMLHttp requests causing JSON data to be overwritten

I am facing an issue where my JSON data is being overwritten by the result of the last XMLHttpRequest made for each country. Is there a way to prevent this from happening? Below is the code snippet in question:

function getDataBetween() {
    for (var i = 0; i < CountryNames.length; i++) {
        var countryName = CountryNames[i];
        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                for (var a = 0; a < CountryNames.length; a++) {
                    dataset[a] = JSON.parse(xmlhttp.responseText);
                    console.log(dataset[a]);
                }
            }
        }

        xmlhttp.open("GET","update.php?country=" + countryName + "&begin=" + beginTime + "&end=" + endTime + "&functionName=getActiveUsers", true);
        xmlhttp.send();
    }

    DrawStructure();
}

I have attempted to implement Promise syntax as suggested here, but I am struggling to apply it effectively in this scenario despite trying multiple approaches.

Answer №1

To prevent overwriting your xmlHttpRequest objects in the for loop, it's important to keep track of separate instances for each request. One solution is to use a closure to create a unique function scope for each iteration of the loop:

function getDataBetween()
{
    for (var i = 0; i < CountryNames.length; i++) 
    {
        (function() {
            var countryName = CountryNames[i];
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200) 
                {
                    for (var a = 0; a < CountryNames.length; a++) 
                    {
                        dataset[a] = JSON.parse(xmlhttp.responseText);
                        console.log(dataset[a]);
                    }
                }
            }
            xmlhttp.open("GET","update.php?country=" + countryName + "&begin=" + beginTime + "&end=" + endTime + "&functionName=getActiveUsers", true);
            xmlhttp.send();
        })();
    }
    DrawStructure();
}

Another approach is to reference this instead of the xmlhttp variable directly within the onreadystatechange handler to avoid using overwritten values:

function getDataBetween()
{
    for (var i = 0; i < CountryNames.length; i++) 
    {
        var countryName = CountryNames[i];
        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange=function()
        {
            if (this.readyState==4 && this.status==200) 
            {
                for (var a = 0; a < CountryNames.length; a++) 
                {
                    dataset[a] = JSON.parse(this.responseText);
                    console.log(dataset[a]);
                }
            }
        }
        xmlhttp.open("GET","update.php?country=" + countryName + "&begin=" + beginTime + "&end=" + endTime + "&functionName=getActiveUsers", true);
        xmlhttp.send();
    }
    DrawStructure();
}

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

The VueRouter is unresponsive and not functioning as expected

I have been delving into Vue. Through the npm install vue-router command, I added vue-router to my project. Subsequently, I incorporated VueRouter and defined my URL paths within the VueRouter instances located in the main.js file. I created an About compo ...

Saving MongoDB query results to a file using the built-in Node.js driver

I have been attempting to save the output of a MongoDB query to a file using the native Node.js driver. Below is my code (which I found on this post: Writing files in Node.js): var query = require('./queries.js'); var fs = require('fs' ...

When I use .fadeToggle, my div transitions smoothly between visible and hidden states

Looking to create a sleek navigation menu that showcases a colored square when hovered over? I'm currently experiencing an issue where the squares are not aligning correctly with the items being hovered. Switching the position to absolute would likely ...

Invoking a C++ dll in the renderer process of a Node.js application with Electron using node ffi

As I work on developing a windows application using electron, my goal is to utilize the ffi-napi to invoke C++ .dll methods. However, I am facing a challenge with the "Passing_Dll.js" file, where the label with id "GenName" is not being updated when clicki ...

How do browsers typically prioritize loading files into the cache?

Out of curiosity, I wonder if the categorization is determined by file names or byte code? It's possible that it varies across different browsers. Thank you! ...

What could be the reason for StaticComponent constantly re-rendering despite having a static state that does not change

I'm trying to grasp the core concepts of how React triggers component re-rendering upon state changes. In the scenario described below, the console.log('hi') statement within the StaticComponent is executed every time the onChange event han ...

Exploring file writing using Node Webkit and JavaScript

When developing my app, I encountered an issue with the 'fs' module not functioning as expected. Despite the code being written to write a file, nothing happens when the app is launched. However, if I start the app using the following command: $ ...

Is there a way to extract a specific element from an array stored within a form element's value?

I am encountering an issue with retrieving values from an array in an HTML form element using jQuery. Despite my efforts to explain and provide code, I am not getting the desired results. Can someone help me understand what is going wrong in my code? Thank ...

Connection error between frontend and backend was encountered

Whenever I try to register on my page and connect it to the database, I encounter an error after pressing the sign-in button... "Uncaught (in promise) TypeError: Converting circular structure to JSON --> starting at object with constructor &apo ...

Functionality that can be utilized repeatedly

I've been struggling to implement a feature for repeatable blocks in my web form. The issue I'm facing is that when I click the buttons, nothing happens even though they work fine when tested in the console. I've been stuck on this problem f ...

Converting a struct to an array format without keys using serialization and deserialization

Is there a way to serialize and deserialize a struct without specifying keys? By using indexes as keys, the order of fields can be preserved which would result in a smaller payload size. I am currently utilizing serde_json and ciborium crates, both of whi ...

Populating SVG element with information extracted from JSON

Hi there! I'm dealing with a JSON file that contains data for 249 countries, each with their respective iso codes. My goal is to declare the iso code as a variable named 'iso' and the number of visitors as a variable named 'visitors&apo ...

Vue: Ensuring one method finishes executing before triggering the next one

I've implemented two methods in my Vue instance; const app = new Vue({ el: '#app', data: { id: null }, methods: { getId: function() { return axios.get('url') .then(response => response.data) .then(i ...

Pass a Json object as a parameter to a Web Api controller in a .NET Core application

This code snippet utilizes Google API with Javascript var output = new Object(); output.PlaceID = place.place_id; output.Longitude = place.geometry.location.lng(); output.Latitude = place.geometry.location.lat(); $.ajax({ headers: { 'Acc ...

Is there a way to retrieve attribute values from a JSON object using JMESPath?

I am searching for the value of the _ISSUE_CURRENCY variable. The JSON data I have is as follows: { '#value': 'VR-GROUP PLC', '_ISSUE_CURRENCY': 'EUR', '_PRICING_MULTIPLIER': 1, '_TYPE ...

Obtaining a value from an array using Google App Script

Having some difficulties with the code snippet provided here. It might be a basic question, but I'm unable to figure out what's going wrong. The issue is that I'm trying to perform calculations on individual values in an array generated fro ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

Utilize Google Apps Script to Import a JSON Object into a Google Spreadsheet

I am currently working on a script that interacts with a REST API to fetch JSON response and then import that data into a Google SpreadSheet. The code I have written successfully calls the REST API and retrieves the JSON object. Now, I need to create a sec ...

Enhance the functionality of Javascript Promise.then by allowing the argument function to accept an extra parameter

In my code, I am currently utilizing ES6 Promise as shown below: const ctx = {} Promise.resolve() .then(() => doSomethingWith(ctx)) .then((retValue) => doSomethingElseWith(retValue, ctx)) I wish to achieve something like this: const ctx = {} u ...

Need to return to the previous page following submission

Is there a way to redirect me to the premontessori page after I submit the form? Below is my function handleSubmit: handleSubmit(event) { event.preventDefault(); <Link to='/premontessori' style={{textDecoration:'none'}} & ...