I have a problem I can't find out myself so any help appreciated.
I have a dynamic cart which is filled with some JSON data. In the cart the shipping costs are also filled from the same json data. The script itself works when a method is available. When a shipping method isn't available for that country the script should say "not available" or something like that. Instead it returns an undefined error which causes the cart not to work. After some searching I found out that when an user comes from country A (which is supported by the cart) the variable "methods" is present in the Json string. When a user comes from country B (which isn't supported) the variable "methods" is not present in the json string. Obviously that causes the error. So what I try to achieve is to check if the variable "methods" is present or not. I found some answers like using typeof, HasOwnProperty, lenght() etc but I can't figure out how I should implement that in the script below.
My script
<script type="text/javascript">
function getPriceDynamicCart(price){
price = parseFloat(price).toFixed(2);
price = '€ ' + price.replace('.', ',');
return price;
}
function loadDynamicCart(){
var url = "{{ '/cart/' | url }}?format=json";
$.getJSON(url,function(data){
var cartHtml = '';
var priceTotal = 0;
var foundShipment = false;
$.each(data.cart.products, function(index, product){
priceTotal = priceTotal + parseFloat(product.price.price_incl);
productTitleLimit = jQuery.trim(product.fulltitle).substring(0, 19);
cartHtml = cartHtml +
'<div class="cart-product"><div class="cart-quantity">' +product.quantity+' x </div><div class="cart-title"><a href="'+ product.url +'" alt="'+ product.fulltitle + '" title="'+ product.fulltitle + '">' + productTitleLimit + '</a></div><div class="cart-price">' + getPriceDynamicCart(product.price.price_incl) + '</div></div>';
});
$.each(data.cart.shipping.methods, function(index, method){
if(!foundShipment && !method.cod && !method.pickup) {
priceTotal = priceTotal + parseFloat(method.price.price_incl);
cartHtml = cartHtml +
'<div class="cart-shipping"><a class="vracht" style="cursor:pointer;" rel="nofollow">Verzendkosten:<br />(Vervallen bij afhalen)</a><div class="cart-price"> ' + getPriceDynamicCart(method.price.price_incl) + '</div></div>';
foundShipment = true;
}
});
cartHtml = cartHtml +
'<div class="cart-total"><div class="total">Totaal(incl. btw): <span>' + getPriceDynamicCart(priceTotal) + '</span></div>';
$('#dynamic_cart').html(cartHtml);
});
}
$().ready(function(){
loadDynamicCart();
});
</script>