Answer the question
In order to leave comments, you need to log in
Why doesn't the value of the variable change?
Why doesn't the value of the totalAllProducts variable change?
ajax returns correct data. But totalAllProducts doesn't change
counterTotal() {
let a = 0;
let idProduct = 1;
var totalAllProducts = 0;
//get cart
if ($.cookie('cart') != undefined) {
var cart = JSON.parse($.cookie('cart'));
} else {
var cart = 0;
}
if (cart != 0) {
for (var i = 0; i < cart.length; i++) {
$.ajax({
url: '/getProduct',
type: "POST",
data: {'id': cart[i].id},
success: function(result) {
totalAllProducts = totalAllProducts + Number(result);
}
});
// let total = cart[i].price * cart[i].quantity;
// console.log(cart[i].price);
}
console.log(totalAllProducts);
}
}
Answer the question
In order to leave comments, you need to log in
Because asynchrony.
This question comes up here two or three times a week.
At the time console.log was called, the data had not yet arrived from the server. Upon arrival of data, the anonymous callback specified in success will be called, then the variable will receive its value.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question