Saturday, July 20, 2019

javascript - why java script doesn't stack inside the while loop



I am trying to check values from a database through sending the values by for loop in ajax request to php file, "each value in request" then the file return variable called "avl" if $data["avl"]==1 so it is available if not it is not available.



The problem is that I check a stream of values and they all must return 1 to continue my process, but the condition doesn't wait until the for loop ends to check. It checks the condition before the for loop starts, even the code is not like that. Ex: it does the condition in line 100 before for loop ends in line 50.



var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var avl_qty = 1;

for (var i = 0; i < cartRows.length; i++) {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var cartRow = cartRows[i]

var titleElement = cartRow.getElementsByClassName('cart-item-title')[0]
var item = titleElement.innerText
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var freequantityElement = cartRow.getElementsByClassName('cart-quantity-free-input')[0]


var quantity = quantityElement.value
var freequantity = freequantityElement.value

alert("before avilability ajax")

$.ajax({
url: "checkavlqty.php",
method: "POST",
data: {


item: item,
quantity: quantity,
freequantity: freequantity
},
dataType: "JSON",
success: function(data) {
alert(JSON.stringify(data));
if (data["avl"] == 0) {
alert("inside condistion")
avl_qty = 0;

}
}
})

}

alert(avl_qty)


It always alerts 1, even the final value of avl_qty is 0.



Answer



The ajax call you are doing inside the loop is asynchronous, this means that when the execution reaches the $.ajax[...] line, it will run "in the background" while the normal execution continues through the loop.



What is most likely happening in your code is that the execution will reach the alert(avl_qty) line before the ajax responses from the loop reach you. You can test this by letting the script run. You'll see that it will execute the alert("before avilability ajax"), then alert(avl_qty) and finally all the alert(JSON.stringify(data)); from the ajax requests.



To solve the issue you will have to wait for the async calls to finish, you can use async/await or even callbacks, here's an example.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...