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