I have a simple .change function that goes to the database and gets some values sets some values, ect.
$('.linequantity').change(function() {
...
$.getJSON(url, function(data) {
$('#TT-' + lineItem).text(parseFloat(data['price']) * quantity);
});
});
What I want to then, is on any of the linequantites changing, I want to update the subtotal. (Yes it’s a catalog type/shopping cart style app). My thought was, lets use a .each
$('.linequantity').each(function(){
...
var url = "jQueryFunctions.php?action=getPrice&quantity=" + quantity + "&customer=" + customerID + "&item=" + lineItem;
$.getJSON(url, function(data) {
subtotal = subtotal + (parseFloat(data['price']) * quantity);
});
});
$('#subtotal').text(subtotal);
when I do this though, I get 0 for the subtotal, if the each even fires at all.
I have tired putting the .each in a function. When I moved the .each into it’s own function it fired more consistently, but the getJSON, which in the .change works just fine gets skipped.
Am I running into a conflict of the first json request isn’t quite complete before I ask for another one?
I am open to a change in methodology, but thing the above has the right idea/start to it.
Any ideas?
EDITS
quantity field
<input type="text" class="linequantity" id="SQ-<?php echo $value['itemNumber']; ?>" name="Quantity" placeholder="#"/>
total span
<span id="subtotal" class="currencyField">$0.00</span>
11:44 EDIT:
I think the .each is hitting before the getJson completes. How can I make sure the json request completed before I do not jQuery
I think you just have a race condition whereby the ajax requests are completing too late. The only way to get around this is to have methods that depend on the requests run after they complete. There are a lot of ways to do this such as using
Deferredand$.when. The simple way would be nice:In the
.eachyou are depending on multiple requests — possibly a lot at a time. I would try to do this in one request (e.g. update your server code to accept a list of items and compute the subtotal instead of just having them one at a time). Otherwise, you have to update the subtotal continuously, which may cause it to flicker visually. It’s also inefficient for the server. You may be able to do something like:…but I’m not sure whether
$.whenwill work with an array like that, or if there is any way to expand the argument list to it.