My code is as follows:
$(".qtyfield").each(function (index) {
if (this.value != "" && this.value > 0) {
var fieldname = this.id;
countme = countme + 1;
var tmpProductID = fieldname.split("_")
var ProductID = tmpProductID[1];
var ShowPrice = $(this).closest('td').prev('td').text();
var Quantity = this.value;
ShowPrice = ShowPrice.replace("$", "");
isItemInCart(ProductID).done(function () {
if (isItemInCartVar) {
updateQuantityByProductID(ProductID, Quantity);
}
else {
addToCartWithQty(ProductID, ShowPrice, Quantity);
}
});
this.value = '';
}
});
I need to ensure that this code block completes (all ajax calls included) prior to running any further statements.
A couple of points..
isItemInCart is a function with an Ajax CallupdateQuantityByProductID is a function with an ajax calladdToCartWithQty is a function with an ajax callMy solution would be to consolidate all this logic in a single call, something like updateCart().
On the client side you would create a list of products that need to be updated, e.g.
[
{productId: 123, quantity: 2, price: 123},
{productId: 456, quantity: 1, price: 200}
]
This data gets sent to the server side where the session data will get updated with the new quantities. Basically, the code on the server side will perform the same logic as you have in all your individual calls, but it will be much faster because there's only a single request.
A single request also reduces the likelihood of session lock contention and improves the consistency of your cart state.
On the client side, there's the advantage of only a single callback function instead of having to create a pipe of individual requests that need to be synchronized (read: big pain in the ass).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With