Jquery - POST, success callback is not getting executed

╄→尐↘猪︶ㄣ 提交于 2020-01-03 02:42:11

问题


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.


回答1:


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');



回答2:


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.




回答3:


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 );
 }); 


来源:https://stackoverflow.com/questions/34510053/jquery-post-success-callback-is-not-getting-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!