When provided with 2 callbacks, the outcome is often undefined

Q1: I am encountering an issue where both callbacks are working, but instead of 2 results, I am getting 4 results with onderhoud+undefined and macro+undefined. How can I resolve this?

Q2: Is there a way for me to pass all the variables from loadMacro in the callback and then use them separately within the callback?

function loadOnderhoud(getData) {  
    var username = window.sessionStorage.getItem("huidigeGebruiker");
    var url = "restservices/gebruiker?Q1=" + username;
        $.ajax({
            url : url,
            method : "GET",
            beforeSend : function(xhr) {
                var token = window.sessionStorage.getItem("sessionToken");
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            },
            success : function(data) {
                var onderhoud;

                $(data).each(function (index) {
                    if (this.geslacht == "m"){
                        onderhoud = (66 + (13.7 * this.gewicht) + (5 * (this.lengte*100)) - (6.8 * this.leeftijd)) * this.activiteit;
                    }
                    else if (this.geslacht == "v"){
                        onderhoud = (655 + (9.6 * this.gewicht) + (1.8 * (this.lengte*100)) - (4.7 * this.leeftijd)) * this.activiteit;
                    }
                    });
                getData(onderhoud);
            },
        });
}

// Load ingredients from JSON test file
function loadMacro(getData) {   
    var username = window.sessionStorage.getItem("huidigeGebruiker");
    var datum = document.getElementById("datepicker").value;
    var url = "restservices/ingredients?Q1=" + username + "&Q2=" + datum;
        $.ajax({
            url : url,
            method : "GET",
            async: false,
            beforeSend : function(xhr) {
                var token = window.sessionStorage.getItem("sessionToken");
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            },
            success : function(data) {
                 var totalCal=0;
                 var totalVet=0;
                 var totalVv=0;
                 var totalEiwit=0;
                 var totalKh=0;
                 var totalVezels=0;
                 var totalZout=0;
                $(data).each(function (index) {
                     totalCal = (this.hoeveelheid * this.calorieen) / 100;
                     totalVet = (this.hoeveelheid * this.vet) / 100;
                     totalVv = (this.hoeveelheid * this.verzadigd_vet) / 100;
                     totalEiwit = (this.hoeveelheid * this.eiwit) / 100;
                     totalKh = (this.hoeveelheid * this.koolhydraten) / 100;
                     totalVezels = (this.hoeveelheid * this.vezels) / 100;
                     totalZout = (this.hoeveelheid * this.zout) / 100;
                    });
                getData(totalCal);
            },
        });

}

function getData(data, dataa)
{
    var onderhoud = data;
    var macro = dataa;
    console.log(onderhoud, macro);
}
loadOnderhoud(getData);
loadMacro(getData);

Answer №1

Here’s a breakdown of the process:

let maintenance;
let macros;
function fetchMaintenanceData(retrieveData) {  
    let username = window.sessionStorage.getItem("currentUser");
    let url = "restservices/user?Q1=" + username;
        $.ajax({
            url : url,
            method : "GET",
            beforeSend : function(xhr) {
                let token = window.sessionStorage.getItem("sessionToken");
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            },
            success : function(data) {
                let maintenance;

                $(data).each(function (index) {
                    if (this.gender == "m"){
                        maintenance = (66 + (13.7 * this.weight) + (5 * (this.height*100)) - (6.8 * this.age)) * this.activityLevel;
                    }
                    else if (this.gender == "f"){
                        maintenance = (655 + (9.6 * this.weight) + (1.8 * (this.height*100)) - (4.7 * this.age)) * this.activityLevel;
                    }
                });
                retrieveData(maintenance);
            },
        });
}

// Load ingredients from JSON test file
function fetchMacrosData(retrieveData) {   
    let username = window.sessionStorage.getItem("currentUser");
    let date = document.getElementById("datepicker").value;
    let url = "restservices/ingredients?Q1=" + username + "&Q2=" + date;
        $.ajax({
            url : url,
            method : "GET",
            async: false,
            beforeSend : function(xhr) {
                let token = window.sessionStorage.getItem("sessionToken");
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            },
            success : function(data) {
                 let totalCalories = 0;
                 let totalFat = 0;
                 let totalSaturatedFat = 0;
                 let totalProtein = 0;
                 let totalCarbs = 0;
                 let totalFiber = 0;
                 let totalSalt = 0;
                $(data).each(function (index) {
                     totalCalories = (this.amount * this.calories) / 100;
                     totalFat = (this.amount * this.fat) / 100;
                     totalSaturatedFat = (this.amount * this.saturated_fat) / 100;
                     totalProtein = (this.amount * this.protein) / 100;
                     totalCarbs = (this.amount * this.carbohydrates) / 100;
                     totalFiber = (this.amount * this.fiber) / 100;
                     totalSalt = (this.amount * this.salt) / 100;
                    });
                retrieveData(totalCalories);
            },
        });

}

function retrieveData(data)
{
    maintenance = data;
}
function retrieveData2(data)
{
    macros = data;
}
fetchMaintenanceData(retrieveData);
fetchMacrosData(retrieveData2);

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

Challenges when utilizing AJAX and JQuery for selecting multiple items and retrieving data from a JSON file

I am currently working on a live search feature that extracts data from a JSON file using AJAX and jQuery. The goal is to make the fetched value clickable and populate a multiselect field with it. Once this is achieved, the plan is to capture the remaining ...

Delayed execution of Ajax request

Currently watching a Youtube video that explains the Call Stack and Event loop when dealing with Async events like Ajax calls. According to the video, JavaScript execution occurs line by line. Let's try running a sample program: var xhttp = new XMLHt ...

Unable to export JavaScript module

In my JavaScript project, I have a module named utilities stored in a file called utilities.js. This module contains basic functions that I want to keep hidden from the global namespace. I know that in order to achieve this, I need to create a module, expo ...

Retrieve the next 14 days starting from the current date by utilizing Moment.js

Looking to display the next 14 days in a React Native app starting from today's date. For example, if today is Friday the 26th, the list of days should be: 26 - today 27 - Saturday 28 - Sunday 01 - Monday 02 - Tuesday ............ 12 - Friday Is ther ...

Transferring unique data objects from servlet to jQuery

I am working on a servlet and my objective is to retrieve a customer object from the process request, so that I can access this object in my jQuery code. Can anyone provide guidance on how to achieve this? e.g. myObject.getMethod() Servlet Code: Cust ...

Why Form Validation in JavaScript is Failing to Display Alerts or Update Input Background Colors

Having created this script to validate my forms, I encountered an issue where leaving a textfield blank does not trigger the expected behavior. There is no red background or alert message displayed as intended. function validateForm() { /* Loop through al ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

Using a loop in a Vue.js slick slider: easy step-by-step guide

While utilizing vue-slick link https://www.npmjs.com/package/vue-slick within a bootstrap modal, I encountered an issue when using a v-for loop to iterate through the items. The problem can be seen in this example: https://i.sstatic.net/PhJCE.jpg. Below i ...

Please incorporate the href attribute into the anchor tag when it is clicked

<section> <a **id="download"** oncontextmenu="return false" > <svg ... </svg></a> </section> <script type="text/javascript"> The following code snippet is designed to ...

Capturing full name from a Windows system using Electron

I am facing issues with retrieving the first name and last name using electron and Node.js. I currently have the username but I require the first name and last name as well. View Image Example I have attempted the following: const username = require ...

Turn off a feature on older buttons

For my project, I am looking to dynamically add specific elements like buttons. However, every time a new button is added, the function call for the old button gets duplicated. var btnElem ='<button type="button"class="doSomething">Button< ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Whenever AJAX is employed, PHP validation consistently presents an error or false outcome, regardless of the conditions being

I have a dilemma with my form. There are only two conditions: If the yourname field is empty, it should return an error. If the email field is empty, it should also return an error. However, I am getting an error even when both fields are not empty. I cann ...

Initiating the onclick event for Input/Form

<form method="POST" onsubmit="return false;"> ... <input type="submit" name="button" value="Login" onclick="require('file.js').submitForm(this.form);"> ... </form> Is there a way to trigger the onclick event of this INPUT eleme ...

Transforming a group of JSON objects into a two-dimensional array

Below is an array of JSON objects: var data = [{ 1: { name: 'Name 1', id: 'one' } }, { 2: { name: 'Name 2', id: 'two' } }]; I want to transform this into a 2-D array like this: var newData ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

Tips on transferring the id value from a modal window to an ajax click event?

I'm having trouble passing the image ID to AJAX for updating it in a modal window. After opening the modal and grabbing the correct ID, I attempt to pass it to AJAX but it shows as undefined. How can I properly pass the ID for further processing? $( ...

React component fails to render even after successful authentication check

Trying to set up a secure route for my application, I encountered an issue with React Hooks where the state is not updated directly. This causes a problem when trying to redirect unauthenticated users, as the initial render treats them as not logged in and ...

What is the best way to customize the appearance of Image tags located inside SVGs, whether they are in separate files or embedded within the code

I am developing a custom SVG editor application and facing an issue with implementing a highlighted effect when an <image> element is clicked. I have successfully accomplished this for other elements like <circle> by adjusting attributes such a ...

Retrieving data from a database using PHP and presenting it in a loop for showcasing in JavaScript

I am currently working on a code and trying to achieve the following output: { title:"<?php echo $sender_fullname; ?>", mp3:"link", }, I want to display this in JavaScript using PHP. // Include database require_once "db.php"; // Get email ...