Retrieve the AJAX response, concatenate the data, and construct a dynamic table

I am facing an issue with assigning my AJAX return as a variable to concatenate.

Here is the sample code:

         function FetchSex() {
            $.ajax({
                url: '/SEX/GetAllSex/',
                success: function (responseData) {
                    console.log(responseData);
                }
            });
         }

         function FetchUsers() {
             var Pistas = null;
             $.ajax({
                 url: '/Users/GetAllUsers/',
                 success: function (dataReceived) {
                     console.log(dataReceived)

                 }
             });
         }

The objective is to concatenate the results. Here are the steps I am following:

var SexInfo = GetSex();
var UsersInfo = GetUsers();

var combinedData = UsersInfo.concat(SexInfo);

An error message shows up saying that both SexInfo and UsersInfo variables are undefined!

I find this confusing.

Your help would be greatly appreciated! =)

Answer №1

Utilize GetSex and GetUsers as asynchronous requests. Make sure to chain your requests and assign variable values within the callback functions.

function GetSex(successCallback) {
    $ajax({
        url: '/SEX/GetAllSex/',
        success: successCallback
    });
}

function GetUsers(successCallback) {
    $.ajax({
        url: '/Users/GetAllUsers/',
        success: successCallback
    });
}

function combineUsers(successCallback) {
    GetSex(function(Sex) {
        GetUsers(function(Users) {
            successCallback(Users.concat(Sex));
        }}
    });
}


var x;

combineUsers(function(data) {
    x = data;
});

Exercise caution to avoid falling into Callback Hell

Answer №2

Oh,

I realized I forgot to declare the variables beforehand:

The final version of the code looked like this:

let Gender;
let People;

function FetchGender() {
        $.ajax({
            url: '/GENDER/FetchAllGender/',
            success: function (data) {
                Gender = data;
                console.log(data);
            }
        });
     }

     function FetchPeople() {
         let Info = null;
         $.ajax({
             url: '/People/FetchAllPeople/',
             success: function (data) {
                 People = data;
                 console.log(data)

             }
         });
     }

I appreciate your help regardless.

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

What are the steps to retrieve JSON data and display it using an unordered list in an HTML document?

My JSON data structure looks like this: { "fID": "00202020243123", "name": "John Doe", "List": ["Father", "Brother", "Cousin"] } When I render this JSON element in my model and view it in the HTML, everything works fine. However, when I try t ...

Prevent side menu from automatically hiding when clicking on the heading

My menu is set up with headings and subheadings. When I click on the headings, it expands to display the corresponding subheadings, but it automatically collapses when clicking on the headings. I want it to stay expanded when clicking on the headings. He ...

How can I navigate through a webpage using Selenium WebDriver and JavaScript?

Currently, I am utilizing the JavaScript API for selenium-webdriver and my goal is to scroll/move down a page in a gradual manner to facilitate visual inspection. Although I am aware that the code below will direct me immediately to a link at the end of t ...

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...

What could be causing the issue with my hour parameter in node-cron?

Having difficulty setting up a cron job to run with node-cron every Monday at 8:30. I've tried using "30 8 * * Mon" and even "30 08 * * Mon", but it doesn't seem to work. Interestingly, "30 * * * Mon" does work and runs every hour on the 30th min ...

Scrolling horizontally in vue-chartjs-chartwidget

I have a question regarding vue-chartjs. I am looking to achieve a similar result to the one demonstrated in this jsfiddle example: http://jsfiddle.net/mbhavfwm/ Below is the code for my Vue.js component (Chart data is passed through params). &l ...

Issue encountered while trying to gather vertex coordinates from a file using Blender's from_pydata function

I encountered the following error: Error: Array length mismatch (expected 3, got 13) TypeError: a float is required Traceback (most recent call last): File "\Test.py", line 393, in from_pydata File "C:\Program Files (x86)\Blender Foundation ...

When using the * selector in jQuery on Chrome, it targets and selects scrollbars

Here's the code I'm currently using: $("*").bind("mousedown.sg", { 'self':this }, this.sgMousedown); This code binds an event listener to all elements on the page, and it functions properly in most browsers except for Chrome. In Chrom ...

Holding onto numerous AJAX requests while disconnected, then dispatching them once the network connection is

I'm working on an application that heavily relies on AJAX requests, requiring the rapid or concurrent sending of multiple calls. The code snippet provided serves as a basic wrapper for sending AJAX POST requests within the app. However, I've enco ...

Learn how to generate a DataTable in C# by parsing multiple nested JSON Objects efficiently

Whenever I receive dynamic JSON data, it could be a JSON array, a simple JSON object, or nested JSON objects. I am attempting to deserialize and convert the JSON object/array into a DataTable for further processing using Newtonsoft.Json. Here is my curre ...

Error message in Leaflet JS: Unable to access property 'addLayer' because it is undefined when trying to display drawnItems on the Map

My attempt to showcase a Leaflet Map with polygon-shaped surfaces encountered an issue. Sometimes, I face the error "cannot read property 'addLayer' of undefined," but when the page is refreshed, the map renders correctly. I am unsure where I wen ...

What is the best way to deliver flash messages using Express 4.0?

Currently, my web application requires authentication, and I am encountering an issue with the signup page. If a user tries to sign up with an email that is already in the database, I want to display an error message. Here is the code snippet I am using on ...

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

Create a script that ensures my website can be set as the homepage on any internet browser

I am currently in search of a way to prompt users on my website to set it as their homepage. Upon clicking "Yes," I would like to execute a script that will automatically make my website the user's browser homepage. I have come across a Similar Thread ...

Can you set up a mechanism to receive notifications for changes in an array variable in Angular?

I'm exploring methods to delay an HTTP request until the user stops interacting. I am considering using the debounceTime() operator from RxJs, but I need this to be triggered by changes in an array that I have defined. Here is the scenario: export c ...

Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order. ...

Is there a way to prevent my token from being exposed when making an AJAX call?

When working on my HTML file, I encountered an issue with a Python Django URL integration where I need to pass a token to retrieve certain information. However, the problem is that my token is exposed when inspecting the page source in the HTML document. ...

Eliminate the registration message from TinyMCE by importing a package

Looking to create a TinyMCE React package, I've been using import { Editor } from '@tinymce/tinymce-react'; However, I'm encountering this message - https://i.sstatic.net/j4Cfw.png To remove the message, typically you would add the AP ...

Is it possible to hide a fixed header on scroll in a mobile device?

I am facing an issue with my Wordpress site where I want the header to hide when the user scrolls. Despite trying various codes, I have been unable to make it work. The reason for wanting to hide the header is that on mobile devices, it causes scroll prob ...

Ways to reuse test cases across different test suites in Protractor

There are some shared test cases that can be utilized across different test suites. For example, suppose suite x and suite y both require the same set of test cases to function properly. To address this, a separate .js file containing the shared code has ...