Ad

Javascript Function Not Getting Executed Properly

- 1 answer

I am calling .getJSON to execute some AJAX scripts in shopify. The callback function has multiple statements but only the first line is getting executed.In the below code when I debug, the control goes to line

jQuery.getJSON('/cart.js', function(cart){

After that is shows the alert box with correct count from cart. However the code below the alert messages are not getting executed. Where am I getting wrong.

function addtocart(prod_handle, variant_id) {
  var found = false;
  var x = 0;
  jQuery.getJSON('/cart.js', function(cart) {
    alert(cart.item_count);
    x = cart.item_count;
    if (x > 0) {
      jQuery.getJSON('/product/' + prod_handle + '.js', function(product) {
        var selected_prod_tags = products.tags;
        for (var index = 0; index < selected_prod_tags.length; index++) {
          if (selected_prod_tags[index] == 'jamshedpur' || selected_prod_tags[index] == 'ranchi') {
            var city = selected_prod_tags[index];
          }
        }
        jQuery.getJSON('/product/' + cart.items[0].handle + '.js', function(product) {
          var cart_prod_tags = products.tags;

          for (index = 0; index < cart_prod_tags.length; index++) {
            if (cart_prod_tags[index] == city) {
              found = true;
              jQuery.post('/cart/add.js', {
                quantity: 1,
                id: variant_id
              });
            }
          }
          if (found == false) {
            alert("Error!! Please select products from same city");
          }
        });
      });
    } else {
      jQuery.post('/cart/add.js', {
        quantity: 1,
        id: variant_id
      });
    }

  });

}
Ad

Answer

Products is undefined in the next two requests you run. Is that just a typo?

Keep in mind that getJSON requires it to be valid JSON or it will fail silently depending on the version of jQuery you have.

jQuery.getJSON('/product/' + prod_handle + '.js', function(product) { var selected_prod_tags = products.tags;

You might also want to look at abstracting some of that code out to separate functions e.g. the add.js call.

Ad
source: stackoverflow.com
Ad