interesting line item properties issue

the blog image

Jul 10, 2013

In the last year I have removed crufty cookie based customization code that exploited Shopify’s cart.attributes to replace it with the more modern line item properties.

It is a pleasurable process and sometimes I have deleted 2000+ lines of goofy customization code that never really worked well with 50 that do. The problem with the old solution is in how Shopify sets up cookies and sessions and how that totally affects the old patterns of using cookies and cart.attributes.

In the move to using Line Item Properties I just had a client inform me of a problem when using them. If you render a nice input text box and assign it a name like “properties[FizzBuzz]” and the customer types in some input like “Shiny ball, arf arf arf” it gets assigned to the product as a line item property and all is well. Now let’s try another input from another customer that reads as “Mike & Mary up in a tree, k-i-s-s-i-n-g.”. When we review this we will be somewhat shocked to see it processed as just “Mike”. The reason is when we post the values to the Shopify cart, the Ampersand character is part of the Ajax parameters and that is not going to fly. If you POST data to the Shopify API to add a product to the cart, the data can be something like

"?quantity=1&variant_id=123456789&FizzBuzz='Coke Please, hold the straw'"

This will work fine. But in the second case we pointed out with Mike and Mary, it will bomb. It would like:

"?quantity=1&variant_id=123456789&FizzBuzz='Mike & Mary up in a tree, k-i-s-s-i-n-g.'" 

And now we’re in some trouble. The Ampersand in the value will mess up the data sent to Shopify and the merchant will receive the Mike but nothing else. Solving this is simple. We use Javascript and a regular expression to turn all the Ampersands that are in the line item property values to the correct representation of %26. Now we submit:

"?quantity=1&variant_id=123456789&FizzBuzz='Mike %26 Mary up in a tree, k-i-s-s-i-n-g.'" 

That satisfies the HTTP POST and works well with the Shopify Javascript API.