0

I have declared a global variable

var cart = [];
var cartTotal;

$(document).ready(function()
{

        if(typeof cartTotal != 'undefined')
{
    alert(cartTotal);
}
else
{
    alert("cartTotal is undefined");
}

        loadJSON();



}); 

I then change it in a function later down the line after going through loadJSON etc.

function addToBasket(item)
{
$.getJSON("products.json", function(result) 
{
    for (var i in result.products) 
    {
        var itemToAdd = result.products[i].idCode;

        if(item == itemToAdd)
        {
            if(typeof cartTotal == 'undefined')
            {
                cartTotal = "";
                cartTotal = cartTotal + parseFloat(result.products[i].price);   
                document.getElementById("currentTotalCost").innerHTML = "£" + cartTotal;
            }
            else
            {
                cartTotal = parseFloat(cartTotal) + parseFloat(result.products[i].price);
                document.getElementById("currentTotalCost").innerHTML = "£" + cartTotal;
            }
        }
    }
});
cart.push(item);
alert(cart);
}   

But when I then try and access the cartTotal elsewhere in another function after changing the value, it's throwing an undefined message, and I'm totally stumped as to why. I've tried setting an alert when it runs loadJSON again, as I know when that will run, but it's just saying undefined, even after going there from the addToBasket.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Navvy
  • 237
  • 3
  • 9
  • 23
  • "But when I then try and access the cartTotal elsewhere in another function after changing the value," — The code you've shared doesn't do that. – Quentin Apr 16 '15 at 23:15
  • Well where is it that it is undefined. My guess is you are treating a asynchronous method as synchronous. – epascarello Apr 16 '15 at 23:16
  • It's probably because you're trying to access that value before it was actually c reated. You need to include the logic to access it inside the DONE callback for the getJSON function – Codey Apr 16 '15 at 23:16
  • For example, the check I've just put in if it's undefined, it always throws undefined, even if I've just ran the addToBasket function, and then loaded something else which runs the document.ready function – Navvy Apr 16 '15 at 23:21
  • Also discovered, if I call a function from within addToBasket, I can access it within there, but still nowhere else... – Navvy Apr 17 '15 at 00:10

0 Answers0