1
votes

In my shopping cart, I want to compare available stock and the quantity the user wants to buy, I don't know why it is not working properly. It works on some items and some it won't work. Even when the item available is greater than item demanded, it keeps saying exceeded and when I input a greater value, it will work.

$(document).on('click', '.add_to_cart', function() {
  var product_id = $(this).attr("id");
  var product_ids = $('#prods_id' + product_id + '').val();
  var product_name = $('#name' + product_id + '').val();
  var product_cat = $('#cat' + product_id + '').val();
  var product_type = $('#type' + product_id + '').val();
  var product_size = $('#size' + product_id + '').val();
  var product_price = $('#price' + product_id + '').val();
  var product_cost_price = $('#cost_price' + product_id + '').val();
  var product_quantity = $('#quantity' + product_id).val();
  var product_unit_quantity = $('#unit_qty' + product_id).val();
  var product_unit_carton = $('#unit_carton' + product_id).val();
  var product_stock_qty = $('#stock_qty' + product_id).val();
  var action = "add";

  if (product_quantity > product_stock_qty) {
    alert("Exceeded Available Quantity");
  } else if (product_quantity > 0) {
    $.ajax({
      url: "action.php",
      method: "POST",
      data: {
        product_id: product_id,
        product_ids: product_ids,
        product_cat: product_cat,
        product_name: product_name,
        product_type: product_type,
        product_size: product_size,
        product_price: product_price,
        product_cost_price: product_cost_price,
        product_quantity: product_quantity,
        product_unit_quantity: product_unit_quantity,
        product_unit_carton: product_unit_carton,
        action: action
      },
      success: function(data) {
        load_cart_data();
        alert("Item has been Added into Cart");
      }
    });
  } else {
    alert("Please Enter Number of Quantity");
  }
});
Start by adding console.log(product_quantity," > ",product_stock_qty); before your test and look in the console - mplungjan
post what this looks like with real values: {product_id:product_id, product_ids:product_ids, product_cat:product_cat, product_name:product_name, product_type:product_type, product_size:product_size, product_price:product_price, product_cost_price:product_cost_price, product_quantity:product_quantity, product_unit_quantity:product_unit_quantity, product_unit_carton:product_unit_carton, action:action} - zer00ne
I have consol.log and it gave me the right result. All is working fine if I remove the check if requested greater than available stock. For some reasons I don't understand, it works for some and wont work for some. - Chidi Okafor
@zer00ne, the variables are all working fine. - Chidi Okafor