Advertisement
hmbashar

Ajax for Add to Card

Jan 2nd, 2024 (edited)
1,045
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 2.07 KB | None | 0 0
  1. jQuery(document).ready(function($) {
  2.     $('body').on('click', '.abcbiz_add_to_cart', function(e) {
  3.         e.preventDefault();
  4.  
  5.         let button = $(this);
  6.         if (button.is('.disabled')) {
  7.             // Exit if the button is disabled
  8.             return;
  9.         }
  10.  
  11.         let product_id = button.data('product_id');
  12.         button.addClass('abcbiz_cart_loading');
  13.         let quantity = button.closest('form').find('.quantity input').val() || 1; // Default to 1 if not set
  14.        
  15.  
  16.         $.ajax({
  17.             type: 'POST',
  18.             url: acbbiz_add_to_cart.ajax_url,
  19.             data: {
  20.                 'action': 'abcbiz_ajax_add_to_cart_handler',
  21.                 'product_id': product_id,
  22.                 'quantity': quantity,
  23.                 'abcbiz_cart_nonce': acbbiz_add_to_cart.abcbiz_add_to_cart_nonce
  24.             },
  25.             success: function(response) {
  26.                 var messageDiv = $('#acbbiz-add-to-cart-message');
  27.                 if (response.success) {
  28.                     messageDiv.html('<p class="success-message">' + response.data.message + '</p>').fadeIn();
  29.                 } else {
  30.                     messageDiv.html('<p>' + response.data.message + '</p>').fadeIn();
  31.                 }
  32.                
  33.                 messageDiv.delay(2000).queue(function(next) {
  34.                     $(this).empty();
  35.                     next();
  36.                 });
  37.             },
  38.             complete: function() {
  39.                 button.removeClass('abcbiz_cart_loading');
  40.             },
  41.             error: function(jqXHR, textStatus, errorThrown) {
  42.                 var messageDiv = $('#acbbiz-add-to-cart-message');
  43.                 var errorMessage = "An error occurred. Please try again.";
  44.                 if (jqXHR.responseJSON && jqXHR.responseJSON.data && jqXHR.responseJSON.data.message) {
  45.                     errorMessage = jqXHR.responseJSON.data.message;
  46.                 }
  47.                 messageDiv.html('<p class="error-message">' + errorMessage + '</p>').fadeIn().delay(2000).fadeOut();
  48.             },
  49.         });
  50.     });
  51. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement