Update old ajax code to current JQUERY version

104 Views Asked by At

I have an old AJAX code that works in JQUERY 1.8.3 but fails with later versions. As I try to keep my code up-to-date and try to avoid deprecated code, I need to update my script.

Current code

$('.productlist input[type=submit]').bind('click', function () {
  var i = 0;
  var a = $(this).closest('.productlist2').find('input[data-productid][value!=]').length;
  $(this).closest('.productlist,.WPproductlist').find('input[data-productid][value!=]').each(function () {
      if ($(this).attr('data-produktfarve') != "") {
          $.ajax({
              url: '?ProductID=' + $(this).attr('data-productid') + '&EcomOrderLineFieldInput_farvevalg=' + $(this).attr('data-produktfarve') + '&Quantity=' + parseFloat($(this).val()) + '&cartcmd=add',
              success: function (data) {
                  i++;
                  if (i == a) {
                      window.location.reload();
                  }
              }
          });
      } else {
          $.ajax({
              url: '?ProductID=' + $(this).attr('data-productid') + '&Quantity=' + parseFloat($(this).val()) + '&cartcmd=add',
              success: function (data) {
                  i++;
                  if (i == a) {
                      window.location.reload();
                  }
              }
          });
      }
  });
  setTimeout(function () {
      window.location.reload();
  }, 500);
  return;
});

I've tried with various new versions of JQUERY get and post request but to no avail.

1

There are 1 best solutions below

0
On

Try this,

$(function(){
    $('.productlist input[type=submit]').on('click', function () {
       var i = 0;
       var a = $(this).closest('.productlist2')
                      .find('input[data-productid][value!=""]').length;
       $(this).closest('.productlist,.WPproductlist')
              .find('input[data-productid][value!=""]').each(function () {
          var myurl = '?ProductID=' + $(this).data('productid');
          if ($(this).data('produktfarve') != "") {
              myurl+='&EcomOrderLineFieldInput_farvevalg='+$(this).data('produktfarve');
          }
          var qty=this.value;
          $.ajax({
              url: myurl+ '&Quantity=' + parseFloat(qty) + '&cartcmd=add',
              success: function (data) {
                  i++;
                  if (i == a) {
                      window.location.reload();
                  }
              }
          });
       });
       setTimeout(function () {
          window.location.reload();
       }, 500);
       return;
    });
});