Wait for AJAX to finish before continuing the loop in Javascript

Is it possible to halt a loop until each AJAX request has returned for every iteration?


for (var i = 0; i < 5; i++) {
     var data = "i=" + 1;
     var ajax = $.ajax({
         url: '/ajax.php',
         type: 'post',
         data: data,
         success: function(result)
         {
           //alert(result);
         }                                                      
     });

     //code to pause the loop here

     ajax1.done(function (result) {
         //code to resume the loop here
     }); 
 }

Answer №1

If you're looking to make asynchronous Ajax calls that execute successively without using a traditional for loop, consider implementing recursion instead.

doAjax (index, maxNumber) {

     var data = "i=" + index;
     var ajax = $.ajax({
         url: '/ajax.php',
         type: 'post',
         data: data,
         success: function(result)
         {
           //alert(result);
         }                                                      
     });
     ajax1.done(function (result) {
         if(index<=maxNumber){
               doAjax(index + 1, maxNumber);
     });
}

To implement this logic, simply call doAjax(1, 5). This will ensure that each Ajax call from 1 to 5 is made only after the previous one has completed successfully.

Answer №2

If you are working with ES6, you have the option to utilize the async / await syntax:

for (let i = 0; i < 5; i++) {
  let data = "i=" + i;
  let result = await $.ajax({
    url: '/ajax.php',
    type: 'post',
    data: data
  });
  console.log(result);
}

(Keep in mind that this should be within an async function.)

Without using this syntax or similar features in JavaScript, you will need to adjust your code accordingly:

function requestRange(start, end) {
  function request(i) {
    if (i >= end) return;
    let data = "i=" + i;
    let ajax = $.ajax({
      url: '/ajax.php',
      type: 'post',
      data: data
    });
    ajax.done(function (result) {
      console.log(result);
      request(i + 1);
    }); 
  }
  request(start);
}

requestRange(0, 5);

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

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

Rendering only anchor tags in a v-html element while excluding others and displaying them as strings can be achieved by implementing specific filtering logic

Is there a way to display only the anchor tag and render other HTML tags as strings within the v-html attribute of my Vue project? Similar to how LinkedIn does it: example I attempted to use the linkifyjs library, but I couldn't find out how to sole ...

The code is functioning properly on both Codepen and JSFiddle

I encountered an issue where my code for the header to display only when scrolling up worked perfectly in jsfiddle or codepen, but failed when I tried it in my own program. It was puzzling because I copied and pasted the same code into both platforms and i ...

Locate the closest array index to ensure precise calculations

While working on a Javascript project, I encountered an issue where I needed to calculate the "Price/Earnings Ratio" from a finance API. However, the API did not have a direct method to retrieve the required value. The formula for computing the Price/Earn ...

CSS- Strategically placing and centering images above specific keywords in (any) HTML content without disrupting the flow of text

My main objective involves dynamically inserting images above text on any given page using a content script. The challenge lies in maintaining the proper alignment of the text after adding the images. To achieve this, I surround the words where the image i ...

Mapping with groups in JavaScript

Is there a way to create a mapping in JavaScript? Currently, I am able to do if (number < 32) { group = 1; else if (number < 72) { group = 2; } else if (number < 100) { group = 3; } else { group = -1; } Instead of this, I am interested ...

Comparing Mongoose and MongoDB in Node.js: Weighing the Benefits of Each

Just starting out with Node.js and noticing the multitude of libraries available to work with MongoDB. The two most popular options appear to be mongoose and mongodb. Can someone provide a comparison of the pros and cons of these extensions? Are there any ...

Ways to retrieve form states within an ajax callback function

Currently developing a block module, I am looking to implement ajax functionality on its configuration forms when a file is uploaded through a managed_file field. When the managed_file hidden field is modified (after successful file upload), an ajax callb ...

What is the best way to retrieve data from the next page in a Protractor test?

I am currently in the process of automating the test for booking a flight. When I enter the credentials on the homepage, click the Submit button, and the browser navigates to the search results page. const EC = protractor.ExpectedConditions; describe( ...

Adding an attribute during an ASP.NET onclick event: A step-by-step guide

How can I dynamically add an attribute to a button when the button is clicked? The attribute that needs to be added is dojotype="dijit.form.Button" void ButtonLogin_OnClick(object sender, EventArgs e) { // code to add the attribute } Here is the HTML f ...

Encountering a Javascript issue specifically in IE7 that is not present in Firefox

Currently, I am working on implementing a JavaScript function for a basic effect: when a dropdown option is selected, a set of additional options will be displayed based on the selection. This functionality is working smoothly in Firefox; however, when I t ...

The Carousel Slider malfunctions when attempting to set up multiple carousels

I recently created a carousel slider that seems to be behaving incorrectly when multiple carousels are added. It should slide by one item at a time. For instance, with only one carousel, it slides by one item; with two carousels shown, it slides by two ite ...

Getting the value of a sibling select element when a button is clicked

Trying to retrieve the selected option value on button click has become a challenge due to multiple groups of buttons and select elements. The key seems to be using siblings somehow, but the exact method remains elusive... <div class="form-group" ng-re ...

Unable to show an image within the <div> element when hovering the mouse

Is it necessary to use the background style image in order to display an image on mouseover of a name? I have implemented a controller and would like the image to be replaced by text within a div tag. Below is my HTML code: <!DOCTYPE html> <html& ...

The functionality of Ajax is currently disabled on the latest mobile Chrome browsers

I have successfully created a modal form with dependent dropdown lists, and I am populating these lists using an ajax call. The functionality works smoothly on desktop browsers and most mobile browsers, but there seems to be an issue on certain newer versi ...

Show only the selected option with jQuery's on change event and disable or remove the other options

My goal is to make it so that when a user selects an option from a dropdown menu, the other options are disabled or hidden. For example, if option "1" is selected, options "2", "3", and "4" will be removed: <div class="abc"> <div class="xyz"> ...

Iterating through a set of HTML elements and making updates using a forEach loop

I have encountered an issue while attempting to update a group of HTML elements within a forEach loop. Initially, everything appears to be functioning correctly up to section 3. However, upon adding a new section, the problem arises where the navigation ba ...

Transferring data from one function to another function

I'm currently working on a role-based access application where I've integrated user roles into JWT tokens. Upon decoding the token, I retrieve information such as id and role. I have implemented a function that checks for the token within the x-a ...

Using Vue.js: Creating a Custom Filter to Easily Filter Table Data

This table contains two columns: Name, and Age. Currently, the search functionality only filters by name. However, I would like to implement filtering by age using a comparison operator such as < or >. If you want to see the code in action, check ou ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...