Uncaught SyntaxError: JSON

Quondy
Pathfinder
97 0 31

Hello,

 

Running an inspection on my website www.mastrozavattistore.com, I got this error

 

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at xhr.onreadystatechange (v1_shopify.js:119:25).

 

It appears at collections and products pages. 

 

What should I do to solve this error?

 

I am using Dawn theme 9.00

Replies 6 (6)
NomtechSolution
Astronaut
1245 112 141

The error message you encountered, "Uncaught SyntaxError: Unexpected end of JSON input," suggests that there is an issue with parsing JSON data on your collections and products pages. This error can occur due to various reasons, such as missing or malformed JSON data. Here are some steps you can take to troubleshoot and resolve the issue:

  1. Review recent changes: Consider any recent changes you made to your collections or products pages, including theme modifications, app installations, or custom code updates. If you made any changes around the time the error started appearing, try reverting those changes or double-checking for any potential issues they may have caused.

  2. Validate JSON data: Check the JSON data being fetched or used on the collections and products pages. Look for any missing or improperly formatted JSON syntax. You can use online JSON validators to validate the data and ensure it is correctly structured.

banned
Quondy
Pathfinder
97 0 31

Thank you for your reply!

In the theme where should I look for the problem? 

 

Quondy
Pathfinder
97 0 31

This is the code that causes the error. 

 

(function() {
  "use strict";
  function setCookie(name,value,days) {
    var expires = '';
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '')  + expires + '; path=/';
  }

  function getCookie(name) {
    var cname = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1);
      if (c.indexOf(cname) == 0) return c.substring(cname.length, c.length);
    }
    return false;
  }

  function getUrlParams() {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

  function buildQuery(params) {
    var q = '';
    for (var key in params) {
      if (params.hasOwnProperty(key)) {
        if (typeof(params[key]) === 'undefined')
          continue;
        q += (q.charAt(q.length - 1) === '/') ? '?' : '&';
        q += key;
        q += '=';
        q += params[key];
      }
    }
    return q;
  }

  function getResourceTitle() {
    var title = document.title,
      pos = -1;
    if ((pos = title.lastIndexOf(' – ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' :: ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' | ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' - ')) !== -1) {}
    if (pos !== -1) {
      title = title.substring(0, pos);
    }
    return title;
  }

  //
  // Init Vars

  var urlParams = getUrlParams(),
    subscriberToken = getCookie('smsub'),
    urlSubscriberToken = urlParams.smsub,
    isTest = urlParams.smtest;

  if (urlSubscriberToken) {
    setCookie('smsub', urlSubscriberToken, 365);
    subscriberToken = urlSubscriberToken;
  }

  //
  // Tracking

  function trackingEnabled() {
    return !!subscriberToken;
  }

  function debug() {
    if (console && isTest) {
      console.log.apply(console, Array.prototype.slice.call(arguments));
    }
  }

  function track(event, params) {
    if (!trackingEnabled()) {
      debug('[sm] error: invalid session');
      return;
    }
    if (!event) {
      debug('[sm] error: invalid `event` parameter');
      return;
    }
    if (!params.resource_type) {
      debug('[sm] error: invalid `resource_type` parameter');
      return;
    }

    params = params || {};
    params.event = event;
    params.subscriber_token = subscriberToken;
    params.resource_title = getResourceTitle();
    params.url = params.url || [location.protocol, '//', location.host, location.pathname].join('');
    if (isTest) {
      params.test = true;
    }

    var url = urlParams.smlocal ? '/collect' : 'https://analytics.smartrmail.com/collect';
    var query = buildQuery(params);
    debug('[sm] track:', event, params, query);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        if (isTest) {
          debug('[sm] track response', data);
        }
      }
    };
    xhr.send(query);
  }

  //
  // Testing

  function getTestEventFromUrl() {
    if (!urlParams.smtracktype || !urlParams.smtrackid) {
      return false;
    }
    return {
      resource_type: urlParams.smtracktype,
      resource_id: urlParams.smtrackid
    };
  }

  var testEvent = getTestEventFromUrl();
  if (isTest && testEvent) {
    track(urlParams.event || 'test', testEvent);
  }

  //
  // Shopify

  function isShopify() {
    return typeof(Shopify) !== 'undefined' && Shopify.shop;
  }

  function initShopify() {
    if (!isShopify() || typeof(ShopifyAnalytics) === 'undefined' || !ShopifyAnalytics.meta) {
    	debug('[sm] shopify disabled');
      return false;
    }

    // Newsletter click event
    if (urlSubscriberToken) {
      track('newsletter_click', {
        resource_type: 'product'
      });
    }

    // Resource events
    if (ShopifyAnalytics.meta.product) {
      track('view', {
        resource_type: 'product',
        resource_id: ShopifyAnalytics.meta.product.id
      });
    } else if (ShopifyAnalytics.meta.page &&
               ShopifyAnalytics.meta.page.resourceType === 'collection') {
      track('view', {
        resource_type: 'collection',
        resource_id: ShopifyAnalytics.meta.page.resourceType
      });
    }

    // Cart events (theme specific)
    Shopify.onItemAdded = function(lineItem) {
    	debug('[sm] shopify event: item added:', lineItem);
      track('add_cart', {
        resource_type: 'product',
        resource_title: lineItem.title,
        resource_id: lineItem.product_id // may be undefined
      });
    };

    Shopify.onCartUpdate = function (cart) {
    	debug('[sm] shopify event: cart update: ', cart);
    };

    debug('[sm] shopify init');
    return true;
  }

  trackingEnabled() && initShopify();
})();
made4Uo
Shopify Partner
3785 710 1096

Hi @Quondy 

 

I did not see this in your console. Is this already fix?

Volunteering to assist you!  Likes and Accept as Solution  is highly appreciated.✌
Coffee fuels my dedication. If helpful, a small Coffee Tip would be greatly appreciated.
Need EXPERIENCED Shopify developer without breaking the bank?
Hire us at Made4Uo.com for quick replies.
Stay in control and maintain your security by avoiding unnecessary store access!
Quondy
Pathfinder
97 0 31

Hello @made4Uo nope. The issue is still there 

Quondy
Pathfinder
97 0 31

This is the code that causes the error. It is from Smartmail app.

 

(function() {
  "use strict";
  function setCookie(name,value,days) {
    var expires = '';
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '')  + expires + '; path=/';
  }

  function getCookie(name) {
    var cname = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1);
      if (c.indexOf(cname) == 0) return c.substring(cname.length, c.length);
    }
    return false;
  }

  function getUrlParams() {
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

  function buildQuery(params) {
    var q = '';
    for (var key in params) {
      if (params.hasOwnProperty(key)) {
        if (typeof(params[key]) === 'undefined')
          continue;
        q += (q.charAt(q.length - 1) === '/') ? '?' : '&';
        q += key;
        q += '=';
        q += params[key];
      }
    }
    return q;
  }

  function getResourceTitle() {
    var title = document.title,
      pos = -1;
    if ((pos = title.lastIndexOf(' – ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' :: ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' | ')) !== -1) {}
    else if ((pos = title.lastIndexOf(' - ')) !== -1) {}
    if (pos !== -1) {
      title = title.substring(0, pos);
    }
    return title;
  }

  //
  // Init Vars

  var urlParams = getUrlParams(),
    subscriberToken = getCookie('smsub'),
    urlSubscriberToken = urlParams.smsub,
    isTest = urlParams.smtest;

  if (urlSubscriberToken) {
    setCookie('smsub', urlSubscriberToken, 365);
    subscriberToken = urlSubscriberToken;
  }

  //
  // Tracking

  function trackingEnabled() {
    return !!subscriberToken;
  }

  function debug() {
    if (console && isTest) {
      console.log.apply(console, Array.prototype.slice.call(arguments));
    }
  }

  function track(event, params) {
    if (!trackingEnabled()) {
      debug('[sm] error: invalid session');
      return;
    }
    if (!event) {
      debug('[sm] error: invalid `event` parameter');
      return;
    }
    if (!params.resource_type) {
      debug('[sm] error: invalid `resource_type` parameter');
      return;
    }

    params = params || {};
    params.event = event;
    params.subscriber_token = subscriberToken;
    params.resource_title = getResourceTitle();
    params.url = params.url || [location.protocol, '//', location.host, location.pathname].join('');
    if (isTest) {
      params.test = true;
    }

    var url = urlParams.smlocal ? '/collect' : 'https://analytics.smartrmail.com/collect';
    var query = buildQuery(params);
    debug('[sm] track:', event, params, query);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        if (isTest) {
          debug('[sm] track response', data);
        }
      }
    };
    xhr.send(query);
  }

  //
  // Testing

  function getTestEventFromUrl() {
    if (!urlParams.smtracktype || !urlParams.smtrackid) {
      return false;
    }
    return {
      resource_type: urlParams.smtracktype,
      resource_id: urlParams.smtrackid
    };
  }

  var testEvent = getTestEventFromUrl();
  if (isTest && testEvent) {
    track(urlParams.event || 'test', testEvent);
  }

  //
  // Shopify

  function isShopify() {
    return typeof(Shopify) !== 'undefined' && Shopify.shop;
  }

  function initShopify() {
    if (!isShopify() || typeof(ShopifyAnalytics) === 'undefined' || !ShopifyAnalytics.meta) {
    	debug('[sm] shopify disabled');
      return false;
    }

    // Newsletter click event
    if (urlSubscriberToken) {
      track('newsletter_click', {
        resource_type: 'product'
      });
    }

    // Resource events
    if (ShopifyAnalytics.meta.product) {
      track('view', {
        resource_type: 'product',
        resource_id: ShopifyAnalytics.meta.product.id
      });
    } else if (ShopifyAnalytics.meta.page &&
               ShopifyAnalytics.meta.page.resourceType === 'collection') {
      track('view', {
        resource_type: 'collection',
        resource_id: ShopifyAnalytics.meta.page.resourceType
      });
    }

    // Cart events (theme specific)
    Shopify.onItemAdded = function(lineItem) {
    	debug('[sm] shopify event: item added:', lineItem);
      track('add_cart', {
        resource_type: 'product',
        resource_title: lineItem.title,
        resource_id: lineItem.product_id // may be undefined
      });
    };

    Shopify.onCartUpdate = function (cart) {
    	debug('[sm] shopify event: cart update: ', cart);
    };

    debug('[sm] shopify init');
    return true;
  }

  trackingEnabled() && initShopify();
})();