Looping through multiple Ajax requestsIn this scenario, we need

Here's the snippet of code I'm working with:

for (var i = 0; i < 20; i++) {
$.ajax({
    type: "GET",
    async: false,
    url: "/MyController/MyMethod",
    success: function (data) {
        if (i == 0) {
            $('#result_progress').hide();
            $('#result_msg').hide();
            $('#details').show();
        } else if (i == 1) {
            $.ajax({
            type: "GET",
            async: true,
            url: "/Import/Finish",
            success: function (data) {
                    ....                        
            });                                            
        }
        if (i < 2) {
            $('#details').html($('#details').html() + 'someText'));
        }                                        
    }
});

}

I'm facing issues with using async: false as it causes my browser to stop functioning. Can anyone suggest an alternative solution?

Answer №1

The issue you are facing is that the variable i holds the end value of the loop when the callbacks run.

To solve this, a common approach is to introduce an immediately invoked function expression to maintain the correct value of i:

for (var i = 0; i < 20; i++) {
   (function(i){
      ... your code
   })(i);
}

By calling the function within the loop, a new scope is created in which i is distinct from the outer variable.

Answer №2

I believe implementing some closure would be beneficial:

function createRequest(index){
   return function(){
      $.ajax({
        type: "GET",
        async: true,
        url: "/MyController/MyMethod",
        success: function (data) {
           if (index == 0) {
              $('#result_progress').hide();
              $('#result_msg').hide();
              $('#details').show();
           } else if (index == 1) {
              $.ajax({
                type: "GET",
                async: true,
                url: "/Import/Finish",
                success: function (data) {
                    ....                        
                });                                            
           }
           if (index < 2) {
               $('#details').html($('#details').html() + 'someText'));
           }                                        
       }
     });
   }
}

for (var i = 0; i < 20; i++) {
    createRequest(i);
}

A potential solution is to utilize a function that retains the value of the index variable in each iteration of the loop by creating a new execution context.

Answer №3

Here's the solution I came up with:

function executeLoop(index, totalLoops, startingPoint) {
    if(index >= totalLoops) return;

    $.ajax({
        type: "GET",
        async: false,
        url: "/MyController/MyMethod",
        success: function(response) {        
            // Execute some code here
            executeLoop(++index, totalLoops, startingPoint);
            // More code execution                                     
        }
    });
}

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

Is there a way to generate and transmit a text file using XmlHttpRequest or $.ajax?

The server is anticipating an html or txt file to be sent from a form named "websitetopdf". The file is dynamically created on client javascript and should only function properly on Chrome. Below is the form that needs to be used for sending: <form ac ...

What steps should I take to show the content on different menu selections?

Check out my full code snippet. <html> <head> <meta charset="utf-8"> <title>Title</title> <link rel="stylesheet" href="https://code.jquery.com/mobile/1.5.0-rc1/jquery.mobile ...

Error in Dimplejs: Line is not visible when series is empty

I have a dimplejs.org line chart set up. I am trying to colorize the Clicks data points from blue to red (blue for fewer clicks and a gradient from blue to red for more clicks). When I set the series as shown below, it works fine but the tooltip only incl ...

Is it possible to toggle between thumbnails and a larger image in a jQuery gallery?

Hello, I am new to website development and I would like to create a jquery based photo gallery for my personal website. One feature that really catches my eye is this one (for example): The gallery has a large thumbnail grid where you can click on a thumb ...

Having trouble with accessing controls within an UpdatePanel?

I am attempting to access Page Controls at Page_Load, execute a database query, and modify the visibility of controls. Here is the Code: foreach (Control thiscontrol in ContentPlaceHolderBody.Controls) { try { if (thiscontrol.ID.Contains("Tex ...

Solving the jQuery Enigma: Why the If Statement Fails to Execute

I am struggling with implementing an if-loop inside my success function for AJAX in my project. The success function retrieves the response text from a python script, which can be either "SUCCESS" or "EMPTY". Although I receive the correct data and my aler ...

Utilizing Express.js and AJAX to transfer JSON data from the server to the client

Having trouble sending JSON from Express.js back to the client, and I can't seem to figure out what's going wrong. routes/editor.js exports.save = function(req, res){ fs.readFile(__dirname + "/../public/index.html", function (err, data) { ...

Enhance the appearance of div elements in GWT/HTML with custom styling

I am relatively new to GWT and have been exploring various options, but I have not yet found a solution to my issue. The challenge at hand involves developing a function schedule system in GWT, where I am working on designing the frontend. We currently ha ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

How can AJAX be utilized with both file and text inputs?

I have a basic form enclosed in a modal window, dynamically generated using jQuery: <form name="altEditor-form" id="altEditor-form" enctype="multipart/form-data" role="form"> <div class="form-group"> <div class="col-sm-5 col-md- ...

I am experiencing an issue where my JavaScript code does not redirect users to the next page even

I'm experiencing an issue with this code where it opens another webpage while leaving the login screen active. I've tried multiple ways to redirect it, such as window.location.href and window.location.replace, but nothing seems to be working. Ide ...

Each time the toggle is switched, an additional AJAX request is sent to the PHP document

I've been working on a function that sends data to a PHP file, which then processes the data. The PHP part works fine, but I'm having issues with the jQuery side of things. Each time I click on a ".work" element and trigger the toggle function, a ...

Tips for efficiently sending multiple ajax requests

Seeking help with my ajax knowledge. Currently, I have a function that is supposed to insert multiple items into an SQL database using a PHP page. However, it seems to only be inserting the last item entered. Here's the code snippet: function submitI ...

"Implement a feature that allows users to click on an image in a queue using

These are the images I have: <img src=img1.jpg class=pic /> <img src=img2.jpg class=pic /> <img src=img3.jpg class=pic /> <img src=img4.jpg class=pic /> <img src=img5.jpg class=pic /> <img src=img6.jpg class=pic /> .Sh ...

What is the process of importing a JSON file in JavaScript?

Is there a way to import a JSON file into my HTML form by calling $(document).ready(function (){});? The properties defined in the JSON file are crucial for the functionality of my form. Can anyone guide me on how to achieve this? ...

Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a differe ...

Azure webhosting blocks the use of AJAX calls

There is a PHP script hosted on my Azure server that returns JSON when accessed through the browser. However, I am having trouble making an AJAX call to this script as none of my requests seem to go through. The issue remains unclear. You can see a failed ...

JavaScript Alert function doesn't wait for execution

I am facing an issue with my Signup page. After submitting the form, I use AJAX POST to send the data. The problem arises in the success function where an alert is triggered immediately without waiting for user input, leading to the execution of the next f ...

When utilizing crispy-forms in Django, I've noticed that sometimes, after the first click of the submit button, rendering failures occur. Strangely, the second time I

I have integrated crispy-forms into my Django project, but I encountered an issue while testing and I am unable to figure out where the mistake occurred. I have included the code below and would appreciate any help in identifying the error: class TestForm ...

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...