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

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Using jQuery, you can unbind and bind events upon the successful completion of

I am currently in the process of developing a slideshow feature for my website. The goal is to have a function triggered when the user reaches the end of the current image list and clicks the right arrow. This function will then initiate an AJAX request ...

Encountered a server issue (500 Internal Server Error) when attempting to send a POST

I have been working on a social media app project using React and MongoDB. However, every time I try to register a user, I encounter a POST error in the console. I have reviewed both my client-side and server-side code, but I am still unable to successfull ...

Iterating variables in Vue.js is reminiscent of the process in AngularJS

When working on my application using vue.js, I am interested in finding the last repeated element within a v-for directive. I understand that in angularjs, there is a similar concept using the $last loop variable in its ngRepeat directive: <div ng-repe ...

Is it possible to use async in the onChange handler of a React event?

Can async be used to pause execution until a function completes within an onChange event? Here is an example: const onChange = async (e) => { console.log(current[e.target.name]); await setCurrent({ ...current, [e.target.name]: e.targe ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

What is the best way to smoothly move a fixed-size div from one container to another during a re-render process?

Introduction Anticipated change Similar, though not identical to my scenario: Situation 0: Imagine you have a container (chessboard with divs for game pieces) and a dead-pieces-view (container for defeated pieces). The positioning of these containers i ...

Jquery fails to function properly unless the page is refreshed

On my MVC page, I have implemented a feature where certain text-boxes are shown or hidden based on the value selected in a drop-down menu using jQuery. The functionality works fine when the page is isolated, but when placed under a menu, it encounters a pr ...

React - Error: you have a syntax problem because there is an unexpected token <

I am working on a project using Express, pg, and react. However, I have encountered some issues with React. Here is the directory of my project index.js var express = require('express'); var server = express(); var path = require('path&ap ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Interactive questioning system using Javascript/jQuery for Quick Responses

Hi there! I'm new to StackOverflow and a bit of a beginner when it comes to javascript/jquery. My current project involves creating a chat interface that looks like SMS text messages. Right now, I have users inputting text and using javascript to disp ...

Initiate an asynchronous request from JavaScript to a C# controller located in a separate directory

Note: Updated at the bottom of question I'm encountering difficulties with making an AJAX call from JavaScript to the C# Controller. The issue seems to be related to the connection URL in my AJAX call within the JavaScript file. If the URL isn't ...

Is there a way to automatically hide a div based on a checkbox value when the page loads?

How can I hide a div in my view when a checkbox is not checked upon page load? <input type="checkbox" class="k-checkbox" id="chkInvoiceStatusActive" asp-for="InvoiceStatus" value="true" /> <input t ...

Avoid re-rendering the template in Vue 3 with pinia when changing state values

I am utilizing Vue3 and Pinia for state management. Here is an excerpt from my Pinia file: export const useCounterStore = defineStore ({ id: 'statusData', state: () => ({ test1: 25, test2: 75 }) }) As for the template I am us ...

Using Javascript Reduce to Manipulate Objects

Here is the data I am working with: let info = [ {id: 1, name: "John Doe", type: "A", amount: 100}, {id: 2, name: "Jane Smith", type: "B", amount: 150}, {id: 3, name: "Alice Johnson" ...

Observing changes to attributes in AngularJS is a useful feature that allows for

I am looking to update the attribute of an element by using its id and have the element respond to this change. After trying to showcase my situation in a plunkr, I encountered issues with even getting ng-click to function properly. My goal is to invoke ...

How can I activate JQUERY when an event occurs?

I am trying to create a selection box where, upon clicking an item on the left, it will shift automatically to the right. However, I am facing issues with using triggers to achieve this functionality. Here is the code I have written. <script type="te ...

The form validation feature is not functioning as expected when integrating mui-places-autocomplete with MUI React

I'm currently working on implementing an autocomplete feature using Google Places API in my project with Material UI React, Redux-Form, Revalidate, and MUI-Places-Autocomplete. Although I've successfully integrated the place lookup functionality, ...

What could be causing the issue where only the latest data is being shown

When I use ajax to retrieve data from my database, the console.log displays all the results correctly, but in my HTML, only the last result is shown. What could be causing this issue? Any help would be appreciated! Thanks! Please keep your response simple ...

Learn about generating PDF files with React Native Expo using the react-native-html-to-pdf library!

I'm currently attempting to execute a 'Hello World' code utilizing the react-native-html-to-pdf library in order to generate a PDF, but I am encountering difficulties setting it up in Expo. Would you be able to provide assistance? I have tri ...