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
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])
}
}