I have various products in a drop down list. If I change the product, then the price changes and the line cost changes commensurate with the quantities being ordered.
Problem: When I select a product, an Ajax call is made to my DB. The correct price
is returned. All good. When I choose an alternative product from the drop down, the product ID and it's var value
changes correctly. However,instead of returning the new correct price, price
shows the value from the previous query. That is to say, it appears that either the price
is being cached, or the arraydata[0].price
is not being cleared or the Ajax call is failing. I do not believe that the Ajax call is failing, as if I make then a further product change, I get a new result, BUT, again the price
value from the query preceding it. Bottom line, my price
is always one query behind. I have tried using cache:false
but that has made difference. I also tried setting the length of the variable result
to 0, that just delivered an undefined
error.
$(".product_id").on('change', function() { //THIS GETS THE VALUE OF A PRODUCT FROM THE DB
var value = parseFloat($(this).val()); // product_id
var row = $(this).parents(':eq(1)').find('input').filter(".cost");
var rowPrice = $(this).parents(':eq(1)').find('input').filter(".price");
// then we use the product_id to grab the price using AJAX //
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
cache:false,
success: function(data) {
data = JSON.parse(data);
var result = data[0].price;
var price = Number(result); //.toFixed(2);
row.data('price', price); // store the row's current price in memory
rowPrice.val(price); // allocate the price to the location called rowPrice
}
});
var quantity = $(this).parents(':eq(1)').find('input').filter(".quantity").val();
if (quantity > 0){
var price = row.data('price');
var cost = (price * quantity);
cost = Number(cost); //.toFixed(2);
var displaycost = $.formatNumber(cost,{format:"#,###.00",locale:"ca"});
row.val(displaycost);
var subTotal = 0;
$("input.cost").each(function(){
var ic = $(this).val();
if (ic !==''){
var inputCost = parseFloat(ic.replace(/,/g, ''));
subTotal += inputCost;}
});
var discount_percent = $("#discount").val();
if(discount_percent ==""){
discount_percent = 0;
}
var calculations = newCalculate(subTotal, discount_percent);
setValues(calculations, $("#updateValues"));
}
});