简体   繁体   中英

Calling a function with AJAX

I'm not sure how to explain this completely, but I hope this will make sense.

I have a function that I've made that calculates the remaining amount to spend to qualify for free delivery when the basket value total falls within certain thresholds.

The basket value is updated with AJAX every time a product is added to the basket.

The add to basket button appears in an AJAX generated modal.

I need my function to be called on every page refresh and also every time a product is added to the basket when the AJAX generated add to basket button is clicked. I'm trying to do all of this with the below, but it doesn't seem to work correctly. One of the problems is that the event fires multiple times when the add to basket button is clicked and another is that the basket total is updated after the event and so the total isn't calculated correctly.

Can anyone explain how I would tidy all off this up?

function totalBag() {
   var standardDeliveryLow = 49.99;
   var standardDeliveryHigh = 64.99;
   var expressDeliveryLow = 65.00;
   var expressDeliveryHigh = 99.99;
   var bagValue = $('#basket-value').text();
   var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));

   if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
       var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
       $('<div class="delivery-message"><p>£'+ standardDifference +' from standar delivery</p></div>').insertAfter('.breadcrumbs');
   } else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
      var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2); 
      $('<div class="delivery-message"><p>£'+ expressDifference + ' from express delivery</p></div>').insertAfter('.breadcrumbs');
   } else {
     return false;
   }
}

$(document).on('ajaxSuccess', function(e) { 
  $('[name="AddItemToBasket"]').on('click', function() {
    $('body').bind('ajaxSuccess.custom', function() {
     totalBag();
     //alert('this works');
     $(this).unbind('ajaxSuccess');
  });
 });
});


totalBag();

EDIT: Have fixed the issue where text was duplicating. Also have added comments for more understanding.


Had a check at the link you specified and tried the following modified code.

As per @ADyson, have removed the click event, which is fixing the multiple event firing.

Regarding your other problem, the total is updated after the event, yes the HTML is getting updated after the ajaxSuccess is triggered. Hence have used the ajaxSuccess event itself to get the basket amount and use it in totalBag fn.

It seems to be working. Kindly confirm:

//Adding empty div so that we can just update the value later
$(document).on('ready', function(){
    $('<div class="delivery-message"></div>').insertAfter('.breadcrumbs');
})

function totalBag(bagTotal) {
   var standardDeliveryLow = 49.99;
   var standardDeliveryHigh = 64.99;
   var expressDeliveryLow = 65.00;
   var expressDeliveryHigh = 99.99;
   //var bagValue = $('#basket-value').text();
   //var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));

   //Using a variable to store the calculated amount with text
   var innerHTML = "";
   if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
       var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
       innerHTML= "<p>£"+ standardDifference +" from standar delivery</p>";
   } else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
      var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2); 
      innerHTML= "<p>£"+ expressDifference +" from express delivery</p>";
   } else {
     return false;
   }
   //Updating the placeholder with new contents
   $(".delivery-message").html(innerHTML);
}

//Gets triggered after every Ajax Success.
//e -> event object, xhr -> The Ajax object which has request and response details, 
//settings -> The settings we used to trigger Ajax, including the request URL
$(document).on('ajaxSuccess', function(e, xhr, settings) { 
    //Checking if the request is of Adding Item to Basket
    if(settings.url.indexOf("AddItemToBasket") !== -1){
        //Getting the response and parsing it
        var resp = xhr.responseText;
        var respObj = JSON.parse(resp);
        //Checking if response is success i.e., item added to cart successfully
        if(respObj.success){
            //Getting the updated Basket value and calling totalBag
            var bagTotal = respObj.basket.subTotal;
            totalBag(bagTotal); 
        }       
    }

});
totalBag(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM