Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript Using Ajax data after call t for data

motorhomer

New Coder
I have a Script that calls data from two tables. The first is all the details for a recipe. It then gets the ingredients from this table and calls second table to get all the properties for the ingredients. Finally when it has all the data it will calculate the recipes statistics (i.e. calories vitamin A etc🙂

The problem I have the second Ajax call needs to run through a loop for all the recipe ingredients (recipeData(recdata). I don't want to call the calculation function till I have all the data.
If I place the calculation function within the .done function it is called every time the for loop is run, but If I place it outside the for loop the function is called before the Ajax request is completed and so the data if undefined.
Any help please

Code:
let ing_name = [];
let ing_qty = [];
let ing_unit = [];
let ing_kcal = [];
$(document).ready(function () {
    callRecipe(); //get recipe data
});
// get recipe data
function callRecipe() {
    var data = { id: '1' };
    var dataSend = JSON.stringify(data);
    $.ajax({
        url: "recipeDB.php",
        type: "POST",
        data: dataSend,
        dataType: "json",
    })
        .done(function (recdata) { recipeData(recdata); });
}
// sort out recipe data into variables then get ingrediants data
function recipeData(recdata) {
    var ing = recdata[1]['ing']
    ing_split = ing.split(';');
    ing_len = ing_split.length;
    for (i = 0; i <= ing_len - 1; i++) {
        var each = ing_split[i].split(",");
        var ingName = each[2].toLowerCase();
        ing_name.push(ingName);
        ing_qty.push(parseFloat(each[0]));
        ing_unit.push(each[1]);
    }
    callIng(ing_name); // call function Ajax to get ingrediants properties 
}
//get ingrediants property from DB for each ingrediants within the recipe
function callIng(ing_name) {
    for (i = 0; i <= ing_len - 1; i++) {
        var name = ing_name[i];
        var data = { id: name };
        var dataSend = JSON.stringify(data);
        $.ajax({
            url: "ingrediantsDB.php",
            type: "POST",
            data: dataSend,
            dataType: "json",
        })
            .done(function (calData) {
                ing_kcal.push(calData[1]['kcal']);
                //calculations(ing_kcal);
            });
    }
    calculations(ing_kcal);
}
// use all ingrediant and ingrediants properties to calculate recipe stats
function calculations(ing_kcal) {
    for (i = 0; i <= ing_len - 1; i++) {
        console.log(ing_name[i] + ' ' + ing_qty[i] + '  ' + ing_unit[i] + '  ' + ing_kcal[i])
    }
}
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom