Pregunta

I'm using Shopify and I'm trying to add an item to the cart using Ajax. The code here does not add and item to my cart. I've spent 5 hours trying to fix this, but no cigar :/

I've included the wrappers in in my theme.liquid.

Here's my code:

<a class="chicken-fingers" onclick="fastcart('515257513','1')">Add to Cart</a>

  <script>  
  function fastcart(variantId, quantity){
  $.ajax({
  type: 'POST',
      url: 'http://name.myshopify.com/cart/add.js',
      data: 'quantity='+quantity+'&id='+variantId,
      dataType: 'json',
      success: function(response){
          $.ajax({
              type: 'GET',
              url: '/cart.js',
              dataType: 'json',
              success: function(cartdata){
                  $('.cart-total-items .count').html(cartdata.item_count);
                  $('.cart-total-price').html('$'+(cartdata.total_price/100).toFixed(2));

                }
            });
        }
    });
  }
 </script> 
¿Fue útil?

Solución

That is not going to work.

Cross-domain Ajax requests don't work and are not allowed. You can only send requests to your own domain name, and cannot send ajax requests to another domain.

You can try out HtmlAgilityPack if you're using ASP.NET!

Actually what /cart/add.js means is that it will move point to your own website's folder cart and the file of add.js. This way you will add the component! In this method, the origin is same, your request will be made through your website and will be sent to the website of yours.

If you want to save the data on their website, you need to use HTTP POST request with the data. And do the coding thing there, and then come back with a response! Or use a plugin for this.

Here are some main articles for cross-domain tutorials:

http://www.bennadel.com/blog/2327-Cross-Origin-Resource-Sharing-CORS-AJAX-Requests-Between-jQuery-And-Node-js.htm

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

http://www.codeproject.com/Articles/185506/AJAX-Cross-Origin-HTTP-request (These guys would help you much)

https://en.wikipedia.org/wiki/Same-origin_policy (Learn here, what requests are allowed and what would fail)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top