Passing a variable by copy in a done call with Ajax

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

for (var i = 0; i < list.length; i++) {
    $.when(
        $.ajax({url: "./dorequest.php?id=" + list[i],
            success: function(response){ jsonFriendlist = response; }}) ).done(
                function(jsonFriendlist) {
                    var friendListObject = JSON.parse(jsonFriendlist);
                    if (!jQuery.isEmptyObject(friendListObject)) {
                        var rawListFriend = friendListObject.friendslist.friends;
                        for (var j = 0; j < rawListFriend.length; j++) {
                            console.log(i);
                            playerLinkList[i].listFriends.push(rawListFriend[j].id);
                        }
                    }
            }
        );

}

The issue I'm encountering is that each call to the "done" function is returning with i = 13, which is the length of the list variable. This happens because the asynchronous nature of the AJAX request means that by the time the done function is called, the main thread has already finished the loop and i equals 13.

My query is how can I prevent this behavior and ensure that i is frozen or passed by copy when the ajax request is sent?

Thank you,

Answer №1

Resolved the issue by implementing a closure.

for (var i = 0; i < playerIds.length; i++) {
    // Passing the parameter "i" to the done functions
    (function(index) {
        var dfd = $.ajax({url: "./dorequest.php?id=" + playerIds[i] + "&requesttype=friendlist",
                success: function(response){ jsonFriendlist = response; }});

        dfd.done(
                function(jsonFriendlist) {
                    var friendListObject = JSON.parse(jsonFriendlist);
                    if (!jQuery.isEmptyObject(friendListObject)) {
                        var rawListFriend = friendListObject.friendslist.friends;
                        for (var j = 0; j < rawListFriend.length; j++) {
                            playerLinkList[index].listFriends.push(rawListFriend[j].steamid);
                        }
                    }
                }
        );
    })(i);
}

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

How come my Ajax response is showing up above my navigation menu?

Every time I scroll my mouse, the admin cards end up covering the navbar, which is really annoying. I can't figure out where I went wrong with this issue. Any assistance would be greatly appreciated. Thank you! #mainsec { height: 100vh; width ...

Update the JSON data based on the specifications outlined in my project

class Transformation { constructor() { this.colHeaders = { error_description: "Description", error_status: "Status", error_code: "Error Code" }; } getColHeader() { return this.colHeaders; } } var jsonData = { error ...

Enhancing Rails functionality with drag-and-drop to modify object attributes

I work with two main models: Collections and Images Collection Model class Collection < ActiveRecord::Base has_many :images, dependent: :destroy accepts_nested_attributes_for :images end Image Model class Image < ActiveRecord::Base belongs_ ...

How can the vertical scroll bar position be reset in Material-Table when pagination is activated?

Whenever I scroll up or down in my Material-Table, and then switch pages, the vertical scroll bar doesn't reset to the top of the table. Instead, it stays where it was before changing the page, causing confusion for users. The only mention of scroll ...

Angular Bootstrap UI - Ensuring only one element collapses at a time

I have integrated the angular bootstrap UI library into my website by following this link: https://angular-ui.github.io/bootstrap/ One issue I am facing is that when I implement a collapsible feature using this library, it collapses or expands every eleme ...

Refresh the view in AngularJS following a successful $http.get request

I have a <ul> in my HTML view that is populated based on a $http.get request. HTML: <div id="recentlyReleased" ng-controller="sampleRecordController as recCtrl"> <h1>Sample Records</h1> <ul> <li class= ...

Tips for stopping the entire webpage from scrolling in Vuetify

Hey there, I'm facing an issue with scrolling on mobile devices and iPads. When I view my site on desktop, there is no scrolling behavior, but as soon as I switch to a mobile device or iPad, the scroll appears. This problem is specific to mobile devic ...

I encountered an error when attempting to integrate Node.js with my terminal in the text editor - permission was denied

After installing node.js and npm, I encountered permission issues when trying to run them from my text editor (VSC). I was advised to open the terminal within the text editor, drag and drop the .js files I'm working on, add "node" and hit "enter" to r ...

What is the best way to utilize AJAX for retrieving numerous data sets from a PHP file?

Currently, I am tackling a project that involves an HTML file containing two different divs: one for "product" and the other for "price". These divs need to display text from rows in a database, which can be accessed easily using a PHP file. Using AJAX, I ...

AngularJS: Index not refreshing after deletion of array item(s) using their indexes

I am attempting to eliminate a specific item from an array variable within AngularJS's scope by using the item's index. If you believe this question is a duplicate, please check out the footnote links for related questions that were not exactly ...

Troubleshooting: Why Files are Not Being Served by

I have noticed that there have been similar questions asked about this topic before, but I couldn't find a solution to my problem by reading the responses. I am trying to get my Node.js app to serve my files, and it seems like the page is correctly r ...

Integrating Gesture Handling in Leaflet JS for two-finger scrolling enforcement

Have you ever noticed that when you're using a mobile device and scrolling down a webpage with a Google map, the map goes dark and prompts you to "Use two fingers to move the map"? https://i.stack.imgur.com/4HD1M.jpg I am interested in incorporating ...

How can we ensure that pointer events return the same coordinates as touch events when the viewport is zoomed in?

I attempted to utilize pointer events (such as pointerdown) instead of using a combination of touch events (e.g. touchstart) and mouse events (e.g. mousedown) to determine the input event coordinates. var bodyElement = document.body; bodyElement.addEvent ...

Using angularJS and Regular Expressions to eliminate the "+" symbols in an email address

I have been given the task of disallowing email addresses with a "+" sign from registering. As someone new to regex, my understanding is that it is better to focus on defining what constitutes a valid input rather than listing what should be excluded. I re ...

How to send data from JavaScript to ASP.NET

$(document).ready(function () { $("#MainContent_ddlFieldName").on("change", function () { var id = $(this).val(); var name = $(this + "option:selected").text(); $('#<%= lblValue.ClientID %> ...

Steps to eliminate a choice from the MUI Datagrid Column Show/Hide feature

I am attempting to customize which columns are displayed on the <GridToolbarColumnsButton/> component within the MUI Datagrid toolbar (refer to the image below) https://i.stack.imgur.com/joZUg.jpg Potential solution: I have been exploring the AP ...

Encountering an issue with the node.js express server when fetching data

I'm running into an issue with the fetch function and node.js. When a button is clicked on my frontend, I want to send a post request to receive an array from my backend as a response. My backend is built using node.js with express, and I'm using ...

Endless scrolling with redux and react

I'm facing an issue while trying to implement infinite scroll in a React-based application that utilizes Redux for state management. I am attempting to dispatch an action on page scroll but have been unsuccessful so far. Below is my code snippet: // ...

ReactJS Enhancements: Additional Selection Feature

Is there a way to access both {board.id} and {board.name} properties in my select value? I tried using example={board.name} but it didn't work. handleChange(event){ this.setState({value: event.target.value}); this.setState({examp ...

Is there a way to determine if a specific string matches a value within an object?

Within my codebase, there exists an object named "codes": var codes = { code1: 'test1' code2: 'test2' } I am looking to determine if this object possesses a specific property and then display the result in the console. if(inp ...