1

I am using the below Jquery code to add items to cart. My intention is to change the "Add to cart" button once the Ajax call is success. However its not happening. Code is below -

  jQuery.post('/cart/add.js', {
              quantity: 1,
              id: variant_id
  }, function(data){
    var myelem = document.getElementById('red') ;
    if (myelem != null){
      document.getElementById('red').id = 'normal';
    }
    $("span").removeClass("hidden-count");
    $(".cart-count").text('1');
    $("#AddToCartText").text("Added");
    $("#AddToCart").css("color","Green");

  });

Currently, the code is adding the item to cart but I am not seeing the intended element manipulations. The jquery to manipulate the elements is correct, because when I remove it from the success callback, and put it just after the AJAX call (without any dependency on AJAX call), in that case the element is getting manipulated.

  1. I have referred to http://api.jquery.com/jquery.post/ to verify the syntax.
  2. I have checked "Console" in Developer tools (Chrome), there are no error messages there.

Please let me know, where I am making mistake.

Tushar Saurabh
  • 687
  • 2
  • 13
  • 27

3 Answers3

4

This works in my cart. Notice the 4th parameter. The id is the variant id:

jQuery.post('/cart/add.js', {id:6028354753}, function(data){
  console.log(data);
},'json');
bknights
  • 14,408
  • 2
  • 18
  • 31
  • thanks it worked. However I do have question, in Jquery documentation, it says the fourth parameter is not required. Evidently it is. Is there any documentation on shopify that I can refer to which lists out the required parameters. – Tushar Saurabh Dec 30 '15 at 08:17
  • 1
    The 4th parameter is needed because,in this case, jQuery was interpreting Shopify's response as html not JSON – bknights Dec 30 '15 at 14:34
0

Have you tried to put some console.log within the callback function? Maybe the code is being executed, but isn't doing what it is supposed to.

Check for the value of variant_id, too.

Marcos Lima
  • 761
  • 1
  • 10
  • 26
-1

You have to add the .done callback to your function in case of success, which you haven't like the example below. That's why you don't get the desired DOM manipulations.

 $.post( "test.php", { name: "John", time: "2pm" })
  .done(function( data ) {
  alert( "Data Loaded: " + data );
 }); 
s33h
  • 183
  • 1
  • 8
  • 1
    even adding .done is not working. Moreover, jquery document doesnt state that .done is required. Below is the example for Jquery site - $.post( "test.php", function( data ) { alert( "Data Loaded: " + data ); }); – Tushar Saurabh Dec 29 '15 at 12:49