1

I'm getting the following error in my javascript. As the title states, this code is working on my localhost, but not when I put it onto my server

Uncaught TypeError: Cannot read property 'push' of null
at addItemToCart (shoppingCart.js:36)
at HTMLButtonElement.<anonymous> (shoppingCart.js:193)
at HTMLDocument.dispatch (jquery-1.11.1.min.js:3)
at HTMLDocument.r.handle (jquery-1.11.1.min.js:3)

I have identified that just before this push function is called that the cart variable is indeed null, but I declare it globally as an empty array, so I'm not sure why that would be.

Code for the function its failing on

var cart = [];
function addItemToCart(name, price, count, id, shortName) {
    for (var i in cart) {
        if (cart[i].id === id) {
            cart[i].count += count;
            saveCart();
            for (var i in cart) {
                if (cart[i].id == 500 && id != 500) {
                    removeItemFromCart(500);
                    alert('because you changed your cart, you will have to reapply your coupon');
                }
            }
            return;
        }
    }
    for (var i in cart) {
        if (cart[i].id == 500 && id != 500) {
            removeItemFromCart(500);
            alert('because you changed your cart, you will have to reapply your coupon');
        }
    }
    var item = new Item(name, price, count, id, shortName);
    console.log(cart);
    cart.push(item);
    saveCart();
}

The error happens at teh cart.push(item); line because cart is null and can not be pushed to. Anymore information someone may need to help feel free and I will shoot it your way.

Thanks in advance!!!

edit:

function displayCart() {
console.log("*** display Cart ***");
var cartArray = listCart();
var output = "<tr><th>Items</th><th>Quantity</th><th>Price</th></tr>";
var output2 = "<tr><th>&nbsp;</th><th>Product name</th><th>Product price</th><th>Quantity</th><th>Total</th></tr>";
var output3 = " <tr><th>Product(s)</th></tr>";
var output4 = "";
console.log(listCart());
for (var i in cartArray) {
    output += "<tr class='item'><td><div class='delete' id='removeItem' data-id='" + cartArray[i].id + "'></div>" + cartArray[i].name + "</td><td><input type='text' value='" + cartArray[i].count + "' readonly></td> <td class='price'>" + cartArray[i].price + "</td></tr>"
    output2 += "<tr class='item'>"
            + "<td class='thumb'><a href='" + cartArray[i].id + "-item.php'><img src='img/catalog/product-gallery/" + cartArray[i].id + ".png' alt='Product Image'/></a></td>"
            + "<td class='name'><a href='" + cartArray[i].id + "'-item.php'>" + cartArray[i].name + "</a></td>"
            + "<td class='price'>$" + cartArray[i].price + "</td>"
            + "<td class='qnt-count'>"
            + "<a class='incr-btn' href='#' id='oneless' data-id='" + cartArray[i].id + "'>-</a>"
            + "<input class='quantity form-control' type='text' value=' " + cartArray[i].count + " '>"
            + "<a class='incr-btn' id='onemore' data-productid='" + cartArray[i].id + "' data-name='" + cartArray[i].name + "' data-quantity='" + cartArray[i].count + "' href='#'>+</a>"
            + "</td>"
            + "<td class='total'>$<em id='test'>" + cartArray[i].total + "</em></td>"
            + "<td class='delete' id='removeAllFromCart' data-id='" + cartArray[i].id + "'><i class='icon-delete'></i></td>"
            + "</tr>";
    output3 += " <tr><td class='name border'>" + cartArray[i].shortName + "<span>x" + cartArray[i].count + "</span></td>"
            + "<td class='price border'>$" + cartArray[i].total + "</td></tr>";
    if ($("#offerCount").attr("data-id") == cartArray[i].id) {
        output4 += +"<a class='incr-btn' href='#' id='oneless' data-id='" + cartArray[i].id + "'>-</a>"
                + "<input class='quantity form-control' type='text' value=' " + cartArray[i].count + " '>"
                + "<a class='incr-btn' id='onemore' data-productid='" + cartArray[i].id + "' data-name='" + cartArray[i].name + "' data-quantity='" + cartArray[i].count + "' href='#'>+</a>";
    }
}
output3 += " <tr><td class='th border'>Shipping</td><td class='align-r border'>Free shipping</td></tr>"
        + "<tr><td class='th'>Order total</td><td class='price'>$" + totalCart() + "</td></tr>"

$("#offerCount").html(output4);
$("#productDisplay").html(output3);
$("#showFullCart").html(output2);
$("#showCart").html(output);
$("#cartTotal").html(totalCart());
$("#totalCart").html(totalCart());
$("#myCartTotal").html(totalCart());
$("#showmyTotal").html(totalCart());
$("#cartCount").html(countCart());

}

function addCouponToCart(coupon) {
if (coupon == 'coupon10' && couponsAdded == 0) {
    var couponReduce = -(totalCart() * .1).toFixed(2);
    addItemToCart('10% off Coupon', couponReduce, 1, 500, '10% off');
    couponsAdded += 1;
    saveCoupon();
}
displayCart();

}

function countCart() {
var totalCount = 0;
for (var i in cart) {
    totalCount += cart[i].count;
}
return totalCount;

}

function removeItemFromCartAll(id) {
for (var i in cart) {
    if (cart[i].id === id) {
        cart.splice(i, 1);
        break;
    }
}
for (var i in cart) {
    if (cart[i].id == 500 && id != 500) {
        removeItemFromCart(500);
        alert('because you changed your cart, you will have to reapply your coupon');
    }
}
saveCart();

}

Code that calls the addCouponToCart Function whenever a post gets set.

   <?php if (isset($_POST['coupon_code'])) { ?>
        <script>
            addCouponToCart(coupon);
        </script>
    <?php } ?>
  • Why is this tagged with PHP? – FKEinternet Jul 27 '17 at 20:54
  • It can be because of content in `saveCart` or `removeItemFromCart` methods. Could you show them? – lunochkin Jul 27 '17 at 20:55
  • 2
    search for `cart=` in your file. you might unknowingly assign `null` to `cart` I guess. – jagad89 Jul 27 '17 at 20:56
  • 2
    Replace the `for in` loops with `for of` of or classic for loop. See https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea on why you shouldn't use a for in loop on arrays. Apart from that, both earlier comments are good places to check too – baao Jul 27 '17 at 20:58
  • Its tagged with php because the cart is innerwoven with php, so it could potentially also be one of the issues, sure I'll add those functions as well. I've searched for the cart= it doesn't exist anywhere else other than in the global declaration. – Julian Dasilva Jul 27 '17 at 20:58
  • How about checking if it's null when the method begins: `if (!cart) { cart = []; }` ? – nocodename Jul 27 '17 at 21:11
  • I've tried updating to a traditional for loop, but I still run into the error of the cart being null (both for the length that i'm trying to set and for the push when I specify a static length). – Julian Dasilva Jul 27 '17 at 21:12
  • @nocodename that was able to bypass the error I faced with adding to cart, but now my addcoupontocart function is undefined. I think maybe the reason why the global variable is not working could be somehow linked to a potential typo? I've posted the functions and will post the code that calls the addCoupontoCart function in the file – Julian Dasilva Jul 27 '17 at 21:26

1 Answers1

1

@codenoname Provided the correct answer of checking for the null cart. That solved the issue, ultimately a lot of functions were not being defined properly. I had wrapped the entire code in a document ready function which seemed to be the issue. Whenever I removed that it worked. Thank you all for your input.

if (!cart) {
    cart = [];
}