What is the reason for sending back an array with no elements in AJAX

I am facing a perplexing issue where my function is returning an empty array when it should contain values. This has me scratching my head, as initially the array 'storearray1' does contain values, but upon subsequent usage, it appears empty. I'm in need of a solution or guidance to debug this problem. Help would be greatly appreciated as this situation has left me feeling confused.

   function f1(){
    var storearray1=[];
    for (var skip = 0; skip < 9000; skip = skip + 500) {
      $.ajax({
          url: "/api/routes?$skip=" + skip,
          success: function(results) {
              //Set result to a variable for writing
              var objs = JSON.stringify(results);
              var routetimeobjs = JSON.parse(objs);
    
              storearray1.push(routetimeobjs['value']);
          }
      });
    
    }
}




    function showresult(){
              console.log(storearray1);//work (refer to image)
              var actualarray=storearray1;
              console.log(actualarray); //does not work- return empty array
        }
showresult();

Console Log for storearray1:

https://i.sstatic.net/PB532.png

Answer №1

Give this a try.

let dataStore=[];
let requests = [];

for (let count = 0; count < 9000; count = count + 500) {
  (function(cnt) {
    let req = $.ajax({
          url: "/api/paths?$count=" + cnt,
          success: function(response) {
              //Save response to a variable for easy access
              let jsonResult = JSON.stringify(response);
              let pathObjects = JSON.parse(jsonResult);

              dataStore.push(pathObjects['value']);
          }
      });

      requests.push(req);
    })(count);
}

$.when(...requests).then(() => console.log(dataStore));

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

Disable reloading when submitting and reset input fields after submission

I am working on developing a website where users can post things and comments without the need to refresh the page. I have encountered some issues while implementing this feature and need some assistance with it. My goal is to allow users to submit comment ...

Issue with inline Javascript not functioning correctly when partial is rerendered in Ruby on Rails version 3.1

I am facing an issue in my project where inline JavaScript in a partial, using some instance variables, does not run when the partial is rerendered after a successful ajax call. Could someone please provide guidance on how to solve this problem? For exam ...

Sending data from a Flask application written in Python to a JavaScript file using AJAX for seamless integration

As I am still in the learning process, please bear with me. I have been making attempts to find solutions, but often encounter issues when sending data of type="POST" from JavaScript to Flask using AJAX. This is the code snippet from my app.py f ...

Ways to resolve - Error: Unable to access 'comments' property of null

I am currently working on developing a blog web application and I am facing an issue with enabling user comments on posts. Despite extensive research and attempts to troubleshoot by searching online, I have not been able to find a solution. I have been str ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

"Repetitive" elements arranged horizontally

My goal is to create a looped row of elements, similar to this design: https://i.sstatic.net/7cC2z.png This row should function like a carousel where clicking the "Next" button changes the current element and positions it in the center of the row. I envi ...

"What could be the reason for web3.eth.getAccounts() method returning an empty array when used with console.log

Upon executing web3.eth.getAccounts().then(console.log);, I encountered an empty array and also received a warning stating ./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. The project began w ...

Utilize Twilio to forward messages to a different phone number

I am seeking a solution to automatically forward incoming messages from one Twilio number to another, based on the original sender's number. For example: If I receive a message on my Twilio number "+14444444444" from '+15555555555', I want ...

Pulling data from a MySQL database using AJAX and PHP to convert it into a JavaScript variable, resulting in

I am attempting to retrieve MySQL data using PHP, convert it to JSON, and then pass it into my JS variables for Chart.js. The JSON generated by PHP appears correct. However, when trying to access the data within my variables, the console is displaying them ...

Refresh the content of an iframe (local HTML) by clicking on buttons

When a user clicks on a button, I am loading an HTML file into a DIV (iframe). The issue arises when the user clicks another button and wants to reload the iframe with a different HTML file. This is the current code snippet: <script type="text/javasc ...

Tips for passing input fields from a React Function component to a function

How can I retrieve the values from 4 input fields in my react functional component using a function called contactMeButtonPressed? The inputs include name, email, company name, and message when the contact me button is clicked. Do I need to implement stat ...

Utilizing libraries in JavaScript

For a while now, I've been grappling with an issue related to importing modules into my main JavaScript script. I recently installed the lodash library via npm and I'm trying to import it into my main script so that I can utilize its functionali ...

Eliminate the word "product/products" from the mini cart in the storefront header, while utilizing ajax

In the header of Storefront, there is a mini cart that displays the price and number of items. I am looking to remove the word "item" or "items" from the .count element. I attempted to override the storefront_cart_link() function with the code below: funct ...

The server's response contained a MIME type of "application/octet-stream" that did not include JavaScript. Module scripts in HTML are subject to strict MIME type checking

Here is the structure of my project: node_modules server.js public: glsl: fragment.glsl vertex.glsl index.html main.js img.jpg style.css I have set up a simple server to serve a three.js animation in server.js const express = require('expre ...

JavaScript has thrown an error stating that the function in my jQuery script is undefined

I encountered an issue Uncaught TypeError: undefined is not a function in my jQuery script. Here is the code snippet: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link re ...

Tips for creating a custom Angular Material modal window that is fully responsive to its parent modal window

Hey there! I've put together a custom modal window in Angular Material by combining the custom modal window example with the Angular Material slider demo. Everything is working well except for the fact that the sliders inside the modal window are not ...

Creating a drop-down menu that aligns perfectly under the bar in Material-UI: What you need to know

While working with Material-UI, I encountered a problem with my drop-down menu. Every time I click on it, it covers the bar instead of appearing below it (see image links below). https://i.stack.imgur.com/1Y8CL.jpg https://i.stack.imgur.com/emf87.jpg Is ...

Tips for implementing a custom filter in an AngularJS JavaScript controller

Can anyone help me with creating a custom filter in an AngularJS JavaScript controller? I need to be able to search for items in an array called segments by their SegmentId. The filter should iterate through the segments array and return the segment that ...

Disallow users from closing the tab or browser window

Is it feasible to create a loop on window.onbeforeunload that opens the current page repeatedly upon tab exit? Take a look at the code below - it works, but browsers may block it as a popup. window.onbeforeunload = function(e) { window.open(do ...

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...