Ad

"Unexpected Token :" Error Using JQuery With The Shopify Ajax Api

- 1 answer

Error

When making a call to the shopify ajax api I am getting an error shown in the developer tools console.

Uncaught SyntaxError: Unexpected token :

Clicking on this error in the javascript console oddly shows the response which is valid JSON:

{
"id":19728251846714,
"properties":null,
"quantity":1,
"variant_id":19728251846714,
"key":"19728251846714:f1a55a69aed71e7c10ca53fd3549edda",
"title":"Ritual Petalos de rosas y vino tinto - Obispado",
"price":139900,
"original_price":139900,
"discounted_price":139900,
"line_price":139900,
"original_line_price":139900,
"total_discount":0,
"discounts":[],
"sku":"",
"grams":0,
"vendor":"Casa Azul Spa",
"taxable":false,
"product_id":1959512244282,
"gift_card":false,
"url":"\/products\/ritual-petalos-de-rosas-y-vino-tinto?variant=19728251846714",
"image":"https:\/\/cdn.shopify.com\/s\/files\/1\/0087\/2267\/7818\/products\/PETALOS_DE_ROSAS_Y_VINO_TINTO.jpg?v=1538589224",
"handle":"ritual-petalos-de-rosas-y-vino-tinto",
"requires_shipping":false,
"product_type":"",
"product_title":"Ritual Petalos de rosas y vino tinto",
"product_description":"\u0026lt;!--\ntd {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}\n--\u003eRitual Pétalos de Rosas y Vino tinto, Exquisito masaje que ofrece bienestar, relajación e hidrata la piel. Realizamos el ritual con mascarilla hidratante y antioxidante, piedras calientes, y cuarzos para ofrecer un delicioso y aromático descanso a todo el cuerpo.",
"variant_title":"Obispado",
"variant_options":["Obispado"]
}

Code

The calling code is:

jQuery.getJSON('/products/'+getProduct.product_handle+'.js', function(product) {

    product.variants.forEach(function(variant) {
      if (getProduct.sucursal == variant.title){
        jQuery.post('/cart/add.js', {
          quantity: 1,
          id: variant.id
        });
      }
    });

  });

Platforms

I'm working with Shopify with the template language Liquid, inside this liquid I have a <script> tag that runs AJAX for calling a method from Shopify.

More information

I know that the error it must have javascript syntax but like I said before I didn't see the error.

Anyone knows about this error?

I appreciate every answer.

Ad

Answer

Try using the long-form of the jquery.ajax call to specify all the AJAX parameters manually:

jQuery.ajax({
  url:'/cart/add.js',
  type: 'post',
  dataType: 'json',
  data: { quantity:1, variant: variant.id }
  // Optional: success/error functions
})

Building on the other answers, it may be that jQuery is expecting one type of response header but is actually receiving a different type.

If this works, you should be able to go back to using jQuery.post by supplying a 4th parameter for the data type ('json'): https://api.jquery.com/jquery.post/

Ad
source: stackoverflow.com
Ad