Tips for preventing premature ajax data requests in a for loop before the previous one has finished

Looking to make multiple ajax requests and return the data one by one in a for loop. However, sometimes new data is sent before the previous request is completed, resulting in incorrect data being returned. This doesn't happen often, but I need help solving this issue.

for (var i=0; i<myarray.length;i++){
        ajaxfunction(myarray[i]);
    }

I've tried using setTimeout in the loop, but the results were incorrect.

I prefer using pure javascript, no JQuery or other library. I came across "complete:" and ".done()" in JQuery, but I'm not sure if they're what I need. Can someone guide me on how to solve this problem with raw javascript?

Answer №1

When tackling this issue, my go-to approach is usually using recursion. However, I am unsure if there are any potential downsides to this method. The code snippet that I typically use looks something like the following:

function handleRequest(currentIndex, list){
    $.ajax({
        url: list[currentIndex],
        ....
        complete: function(){
            //perform actions here
            if (currentIndex + 1 < list.length) handleRequest(currentIndex + 1, list);
        }
    });
}

handleRequest(0, arrayToProcess);

Answer №2

To overcome the challenge of completing one ajax call and waiting for another request until the first one is finished, a recursive call was utilized to work its magic.

var queue_element = ["a","b","c","d","e","f","g"];

var execute_queue = function(i){    
 $.ajax( {    
    url: queue_element[i],
    success: function(
    {
        i++;    // moving on to the next queue entry

        // checking if next entry exists
        if (queue_element[i] != undefined)
        {
            execute_queue(i);
        }
    }

  }); // end of $.ajax( {...

}; // end of execute_queue() {...

var index = 0;

execute_queue(index); // let's go!

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

Nested Checkbox in a dropdown menu option

After successfully creating checkboxes inside a dropdownlist box, I am now attempting to have a checkbox appear once another checkbox is clicked. For example, when the user checks "Documents," a set of sub-checkboxes should appear below it. E.g. []Docume ...

Is it possible to determine the height of a div after it has been rendered using the .resize method?

In my current structure, <div id="A"> <div id="A1"> <div id="B1"></div> <div id="B2"></div> </div> <div id="A2"></div> </div> A2 and B2 contain tables, while B1 has 4 checkboxes. I&a ...

Tips for incorporating a visible marker beside the dropdown arrow

When developing my React application with React hooks forms, I have a select component where I need to include a clear indicator 'x' icon next to the dropdown icon. The current select component code is: <Form.Control size="sm" as=&q ...

What could be causing my secretive table to not show up when the button is clicked?

I have created a table with its display value initially set to none in the CSS. In my JavaScript code, I wrote a function to reveal this table. However, even after adding an event listener to a button to execute the function on click, the table is not bein ...

What is preventing the direct passing of the dispatch function from a useState hook into an onClick handler function?

const Counter = () => { const [count, setCount] = useState(0); // Uncommenting the line below would result in an infinite loop because it directly invokes setCount(count + 1) on render. // This causes the component to continuously re-render and up ...

Utilizing jQuery and AJAX, execute a PHP query based on the user's input and showcase the query's outcome without reloading the page

For the past 24 hours, I've been on a quest to find a solution. Although I've come across similar inquiries, either the responses are too complex for my specific scenario (resulting in confusion) or they are of poor quality. The crux of my issue ...

How can I retrieve button clicks with JQuery DataTables mRender?

I am currently using the following ajax call: $('#stlmtddel').click(function(event) { var customerid = "<%=customerid%>"; var appointofcaid = "<%=appointofcaid%>"; var kindcontrolid = "<%=kindcontrolid% ...

The localStorage is currently being updated, however there seems to be an issue with the output where false is being mistakenly interpreted

My goal is to show the <BR/> component when the value is true, otherwise display the <Nothing/> component. Despite the value being false, the <BR/> is still appearing for some unknown reason. PC.js code: import React,{useContext, useStat ...

What is the method for determining the line number of a specific string within a byte array?

Looking for: The location of a function definition within a code file. What I have: The code file. The byte index where the function definition begins and its length in bytes. How can I determine the line number of this function in the file? My plan: ...

Wordpress throws a fatal error stating "Attempting to call a method on an invalid object" unless it's not being used as a template

Encountering a "Fatal Error: "Call to a member function get_var() on a non-object" when using the following code in search.php: global $owndb; $testtable = $owndb -> prefix. "stuff"; $values = $owndb->get_var( "SELECT COUNT(*) FROM $testtable" ); ...

Tapping into the power of jQuery

I am struggling to achieve the desired effect of clicking on an element and having it return to its original state with another click. I attempted writing additional code for a second click, but it didn't produce the intended outcome. The toggle featu ...

The page is having trouble loading images

My goal is to display sliding images in a web application using Bootstrap carousel. The images are fetched from the backend and stored in the 'images' state. Below is the JSON format of the data that is retrieved: images:[ { SNO:'1', NA ...

Suggestions for ASP.NET Dialog Boxes

Exploring the world of dialog boxes in ASP.NET has been quite intriguing. The way they function in Web-based applications is definitely different from what I've experienced in Windows applications. Currently, I have an ASP.NET form with its own submi ...

Routing in Next.js to create custom URL slugs for usernames, like (site.com/username), is a

I have a requirement to create username pages on my website, where each username will have its own page like site.com/jack The current folder structure I am using is pages > [user] > index.js, but this setup causes issues when someone tries to acces ...

Retrieving an Angular Application directly from the Server

In order to ensure user authentication from the backend before any other code loads in my Angular app, I need the initial request sent to the backend to check if the user is authenticated. Only once the user has been verified as authenticated can the app b ...

Error Message: "Oops! It looks like you are trying to access a property or method

I am in the process of developing a static website that includes tabs (a reactive property), each containing multiple cards (also a reactive property) with images and text. Recently, I encountered the following warning: [Vue warn]: Property or method &qu ...

Send form data in JSON format without refreshing the page

I am currently developing a submit form that does not require a page refresh. The code I have is functioning perfectly, but I was wondering if there is a way to send the data from the form in Json format to my back.php file so that I can avoid declaring al ...

Seeking assistance in the development of a visual depiction of device orientation through JS

My goal is to visually represent the device orientation values alpha, beta, and gamma by creating a series of "bars" for each value. Currently, I have managed to display only the values in plain text using innerHTML. However, I envision these bars moving i ...

Checking the validity of a React form within componentDidUpdate()

I am currently working on a form that involves a lot of complex logic, including auto-filling fields based on user input. It is also crucial for me to provide live validation while the user is typing. Initially, I manually called validators depending on t ...

Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript. Similar to how you would add a new modal in jQuery with $("body").append(" ...