Data is present in a JavaScript array, yet it is returning a value of

In my quest to create an array of User IDs for an AJAX Post Request, I encountered a strange issue. Despite successfully retrieving and displaying the User IDs individually in console.log, once I push them to the connectionData array, accessing specific indices returns undefined. Additionally, when checking the length of the array with

console.log(connectionData.length)
, it shows 0. I suspect this may be due to a synchronization problem, but I'm unable to pinpoint the solution despite consulting similar posts.

const prepareUserDataForConnection = function(){

    var connectionData = [];
    var currentUser = 'robert';
    var currentUser = 'chris';
    console.log(currentUser);
    console.log(followedUser);

    $.ajax({
        type: 'GET',
        url: '/api/currentuserinfo/',
        data: {
            'current_user': currentUser
        },
        success: function(data) {
            let currentUserId = JSON.stringify(data[0].id);
            console.log('Current User Pk is: ' + currentUserId);
            connectionData.push(currentUserId);
        }, 
    });
    
    $.ajax({
        type: 'GET',
        url: '/api/followeduserinfo/',
        data: {
            'followed_user': followedUser
        },
        success: function(data) {
            let followedUserId = JSON.stringify(data[0].id);
            console.log('Followed User Pk is: ' + followedUserId);
            connectionData.push(followedUserId);
        },
    }); 
    console.log(connectionData) 
    console.log(connectionData[0]) 
    console.log("Array length is: " + connectionData.length) 
};

To offer insight into the issue, I've attached a screenshot: https://i.sstatic.net/0H9nU.png

Answer №1

Give this Promise-based approach a try

function ajaxPromise(obj) {
    return new Promise(function (resolve, reject) {
        obj.success = resolve;
        obj.error = reject;
        $.ajax(obj);
    });
}
const prepareUserDataForConnection = function () {
    var currentUser = 'samantha';
    var followedUser = 'daniel';

    return Promise.all([
        ajaxPromise({
            type: 'GET',
            url: '/api/currentuserinfo/',
            data: { 'current_user': currentUser }
        }),
        ajaxPromise({
            type: 'GET',
            url: '/api/followeduserinfo/',
            data: { 'followed_user': followedUser }
        })
    ]);
};

prepareUserDataForConnection().then(function (connectionData) {
    console.log(connectionData)
    console.log(connectionData[0])
    console.log("The array length is: " + connectionData.length)
    // Implement your logic here using the connectionData
}).catch(function (error) {
    console.log(error);
});

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

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

My discord.js bot remains silent in response to a user's message, even when no errors are present

My Discord bot is using version 13.1.0 of discord.js and my Node version is 16.7.0. I utilized the commands npm init to generate a package.json file and npm install discord.js to install the Discord package. The code for the bot is written in index.js, an ...

Limiting the number of checkboxes selected in a Checkbox Group based on

I am working on a checkboxGroupInput that has 4 options (denoted as A, B, C, D). My goal is to restrict the selection to only 2 choices. The user should be able to pick a 3rd option. In this scenario, only the newly selected (3rd) and previously selec ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

Having trouble implementing table row selection with semantic-ui table

I am currently in the process of adopting Semantic-UI, but I am encountering some issues. Specifically, I am struggling to make row selection work in a table. Below is the sample HTML I am using from Semantic-UI: <table class="ui selectable celled tab ...

Is it advisable to generate ajax responses on the server side?

Just starting out with Django and Ajax, looking for some advice. I have a question about best practices in web design: Should a view function that is called using Ajax return data structures and let the client-side (JavaScript) handle rendering HTML pages ...

Show that a CPU-intensive JavaScript function is executing (animated GIF spinners do not spin)

Displaying animated indicator or spinner gifs, then hiding them, is an effective way to communicate to the user that their action is being processed. This helps to assure the user that something is happening while they wait for the action to complete, espe ...

Merge two flat arrays together based on their index positions to create an associative array with predefined keys

These are my two arrays: Array ( [0] => https://google.com/ [1] => https://bing.com/ ) Array ( [0] => Google [1] => Bing ) Here is the desired JSON output: [ { "url": "https://google.com/", ...

Discovering the mean value from a data set in a spreadsheet

I have been tasked with creating an HTML page for a car dealership using JQuery and Bootstrap 5. The goal is to utilize Bootstrap 5 to accomplish the following: Set up a table with appropriate form input elements that allow users to input four (4) quarter ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

Transferring information from one webpage to another using AJAX or embedding it with an iframe

I recently received an address with a basic HTML structure containing numbers. I attempted to display it using an iframe, which worked when tested separately but encountered a connection refusal error when embedded in my page. Alternatively, I tried AJAX ...

Set the RegEx so that the entire match is non-capturing

Recently, I've been working with a regex pattern that looks like this: const newRegex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/; const finalResult = "1988-02-01 12:12:12".match(newRegex); console.log(finalR ...

Using Fullcalendar Moment to retrieve the current time plus an additional 2 hours

Trying to tackle this seemingly simple task using moment.js in conjunction with Fullcalendar. My goal is to retrieve the current time and then add two hours to it. Within the select method (or whatever terminology you prefer), I currently have: select: f ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

How to optimize updating object properties with setState?

Is there a more efficient way to rewrite this code? For example, would using setState(ContentStore.getAll()) achieve the same outcome? I believe this approach appears overly cluttered and any method to simplify the code for readability would be greatly app ...

Trigger jQuery when a breakpoint has been met

I am working on a responsive design that has multiple breakpoints. Within the content, some block dimensions are calculated using jQuery. Whenever the viewport changes, these dimensions also change and therefore the calculation needs to be re-run. How can ...

What is the correct way to properly enter a Svelte component instance variable?

Currently, I am delving into learning Svelte and specifically exploring how to bind to a component instance as demonstrated in this tutorial: As I progress through the tutorial, I am attempting to convert it to Typescript. However, I have encountered an ...

Storing user's input data from a multi-step form into a cookie with the help of ajax

Is there a way to create a multipage form that saves data into a database, allows users to close their browser before completing it, and repopulates with previous session values when they return? I understand that using a cookie is necessary for this tas ...

Coding with a combination of JavaScript, AngularJS, and manipulating brackets

I am currently performing the following action: myArray.push(pageCount); After that, I end up with something like this: $scope.myArray = Pages.getAllPageCount(); Finally, when I utilize AngularJS to display it in my .html file. {{myArray}} If there i ...