Import several JSON files

var address = [ "data/somedata1.json", "data/somedata2.json", "data/somedata3.json", "data/somedata4.json", "data/somedata5.json"];

There is also a function available to import these files:

function readData()
{
    var loadFile = function (filePath, done)
    {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", filePath, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.onload = function () { return done(this.responseText) }
        xhr.send();
    }
    
    address.forEach(function (file, i)
        {
            loadFile(file, function (responseText)
            {
                jsonData[i] = JSON.parse(responseText);
                if(i === 4)
                {
                    fill(jsonData);
                    document.getElementById("el").innerHTML = jsonData[2].title3;
                    Dosomething(jsonData[0])
                }
            })
        })

}

All the JSON files have an exact size of 150kb. However, there seems to be an issue where sometimes when running this code on a website, jsonData[0] turns out to be undefined. This inconsistency in loading data raises the question of what might be going wrong. Is there a way to optimize this code for better assurance that all files are loaded correctly?

Answer №1

One particular concern is that even for relatively small files, there is no guarantee that the downloads will finish in sequential order. To address this issue, it would be more effective to maintain a separate variable to keep track of the number of completed downloads:

function retrieveData() {
  var fetchFile = function(filePath, done) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", filePath, true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.onload = function() { return done(this.responseText) }
    xhr.send();
  }
  var completeCount = 0;
  fileList.forEach(function(file, i) {
    fetchFile(file, function(responseText) {
      jsonData[i] = JSON.parse(responseText);
      completeCount++;
      if(completeCount === fileList.length) {
        populate(jsonData[4]);
        document.getElementById("el").innerHTML = jsonData[2].title3;
        DoSomething(jsonData[0])
      }
    });
  })
}

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 default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Choosing an item in an AngularJS select directive from an external origin

I'm currently working on developing a form using Angular JS for editing venue details such as address and city. The backend system is powered by Django and offers a REST API (Django Rest Framework) which I am interfacing with through Restangular serv ...

What is the best way to send multiple parameter values from jQuery to a Laravel controller?

I am facing an issue with my code where I don't understand how to send multiple parameters from jQuery to the controller. Below is the route: Route::get('/listcdix/{id}/detail/{asnumber}', ['as' => 'remindHelper', & ...

After I click on an operator button, the display on my HTML calculator does not reset

function aClick(){ if(a === undefined){ numberButtons.forEach(button => { button.addEventListener("click", addNumber) }); operatorButtons.forEach(button => { button.addEventListener(' ...

Updating model values while dragging with Angular Dragular

Currently, I am experimenting with dragula and its newer version, dragular, on some sample projects. One specific dilemma I am facing involves the implementation of drag and drop functionality in an Angular project. My query pertains to utilizing a list o ...

Is there a way to transform a PNG image binary string into base64 encoding without saving it to disk?

After successfully passing an image as a binary string out of puppeteer's page.evaluate() function back to node.js, I used the following code: async function getBinaryString(url) { return new Promise(async (resolve, reject) => { const ...

How to utilize Vue method for accessing DOM elements

I'm working on a container with various elements like h1, p, etc. The container has a background and I'm trying to create a method to move it based on mouse coordinates. However, I'm facing an issue where the e.target is showing me ele ...

Display a default value if the state's value is not defined | Vue.js 3

In a Vuejs 3 component, the code below is functioning perfectly with no issues. However, I am looking to display something specific when there is no output: <td> {{ $store.state.output[0].address }} </td> If the above code is undefined or does ...

having trouble parsing JSON data

Recently, I decided to experiment with JSON and utilized json_encode to generate a JSON object structured as shown below: [{ "timestamp": "12\/16\/2013 0:00", "curr_property": "7211", "curr_property_cost": "123", "day_pro ...

Using jQuery to convert JSON data into an array

My JSON data structure is as follows: { "default": [ [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ] ], "direct": [ [ 13 ...

Transmitting information through ajax and fetching it using Request.Form[""]

My struggle lies in passing parameters from a js script to an aspx.cs page. Interestingly, when I exclude the following line: contentType: "application/json; charset=utf-8" from my ajax request, the data received by Request.Form["ORDER"] appears as {%7b% ...

Analyzing Varied Date Formats

I'm looking to create a function in AngularJS that checks if a given date is after today: $scope.isAfterToday= function(inputDate){ if(inputDate > Date.now().toString()){ return true; } else { return false; } } The iss ...

What is preventing me from retrieving the coordinates from the marker in the Google Maps Places API?

Is there a way to obtain the latitude and longitude from a marker in google maps when it is relocated to another position? I have researched and located the solution, however, I seem to be encountering an issue. While I can successfully retrieve the coord ...

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

Adjust the width of the graphics on both sides of the text based on the length of the text content

Is there a way to center an H1 tag between two graphics using CSS or jquery/javascript? The width of the H1 text will vary depending on the page. The dot on the left should remain at the edge of the site, and the line should extend to meet the edge of the ...

A step-by-step guide on adding multiple rows in Laravel

I'm facing an issue when trying to insert multiple rows into a Laravel database. The error message I receive is as follows: Array to string conversion (SQL: insert into `equipments` (`created_at`, `driver_id`, `price`, `product_id`) values (2019-04-1 ...

When utilizing JSON tag, an empty array [] is returned, which conflicts with gson's expectation

I am currently utilizing the GSON Library for parsing my JSON data. In some cases, certain tags are expected to contain string values (not arrays). The issue arises when an element ends up being empty [], resulting in this error message displayed on the c ...

Troubleshooting: Missing JQuery Header in Table

I'm currently working on creating a table using JQuery and everything seems to be functioning properly, except for one issue - the header is not displaying. I have defined the header, appended it to the table, and then added the column names to the he ...

Ant Design - Select - Automatically close dropdown when no data is available

I attempted setting notFoundContent to undefined, however it did not resolve the issue. Are there any other possible solutions for this problem? ...

At times, Firefox may fail to fully showcase an image in fullscreen mode

Currently, my goal is to showcase an image in fullscreen mode using JavaScript. (Refer to the Fullscreen API - https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API) JavaScript snippet: var requestFullscreen = function(el) { if(el.requestFullsc ...