添加优惠券时,ajax购物车未使用产品更新购物车

时间:2017-02-13 18:30:49

标签: php jquery ajax magento

如果我关闭购物车并刷新页面,那么它会填充,但一旦添加优惠券代码就不会填充。任何帮助将不胜感激。

这是我的代码:

var TMAjaxCart = Class.create();

TMAjaxCart.prototype = {

    tmAjaxItemWrapperClass      :'.tm_ajax_item_wrapper',
    tmAjaxCouponWrapperId       :'tm_ajaxcart_coupon_wrapper',
    minicartCouponWrapperId     :'minicart_coupon',
    tmAjaxItemActionClass       :'.tm_ajax_item_action',
    tmAjaxItemFormClass         :'.tm_ajax_item_form',
    tmAjaxItemFormUpdateClass   :'.tm_ajax_form_update',
    tmAjaxItemFormCancelClass   :'.tm_ajax_form_cancel',
    ajaxCartItemsWrapper        :'ajaxcart-items-table',
    miniCartItemsWrapper        :'minicart_list',
    ajaxEditItemsClass          :'edit_link',
    ajaxRemoveItemsClass        :'remove_link',
    ajaxCartWishlistItemsClass  :'wishlist_link',
    ajaxCartItemFormIdPrefix    :'form_ajaxcart_',
    ajaxCartItemActionsIdPrefix :'ajaxcart_actions_',
    ajaxCartType                :'ajaxcart',
    minicartType                :'minicart',
    myCartQty                   :'my_cart_qty',
    minicartQty                 :'my_cart_qty2',
    ajaxcartQty                 :'my_ajaxcart_qty2',
    ajaxCartMessagesArea        :'tm_ajaxcart_msg',
    minicartMessagesArea        :'tm_mini_msg',
    ajaxCartShippingZipForm     :'shipping-zip-form',
    ajaxCartShippingMethodForm  :'co-shipping-method-form',
    ajaxCartShippingButtonClass :'.tm_shipping_estimator_submit',
    ajaxCartShippingTotalClass  :'.tm_shipping_estimator_total',
    ajaxCartShippingWrapper     :'tm-shipping-estimator-wrapper',
    ajaxCartTotalsAreaId        :'shopping-cart-totals-table',
    minicartTotals              :'minicart_totals',
    ajaxCartApplyCouponClass    :'.apply-coupon',
    ajaxCartCancelCouponClass   :'.cancel-coupon',
    ajaxCartCouponFormId        :'discount-coupon-form',
    minicartCouponFormId        :'coupon-form',
    ajaxCartCouponCodeInputId   :'coupon_code',
    minicartCouponCodeInputId   :'coupon_code_mini',
    ajaxCartSelectWrapperClass  :'base_ajaxcart',
    minicartSelectWrapperClass  :'base-mini-cart',
    globalLoader                :'please-wait-quick-view',
    minicartLoader              :'minicart-loader',
    minicartPopupId             :'minicart-popup-item',

    /**
     * constructor
     */
    initialize: function(type, urls) {
        this.type                 = type;
        this.urls                 = urls;

        //define ajax success methods
        this.itemOnSave           = this._ajaxItemSuccess.bindAsEventListener(this);
        this.estimatorOnSave      = this._ajaxShippingEstimatorSuccess.bindAsEventListener(this);
        this.shippingMethodOnSave = this._ajaxShippingMethodSuccess.bindAsEventListener(this);
        this.couponOnApply        = this._ajaxCouponSuccess.bindAsEventListener(this);

        //init listeners related to cart type
        switch(this.type) {
            case this.ajaxCartType:
                this.initCheckoutCartListeners();
                this._minicartAnimationDisable();
                break;
            case this.minicartType:
                this.initMinicartListeners();
                break;
        }
        // updates height on mini cart list
        $j(window).resize(function() {
            var mini_ajax_cart = TMAjaxCart.prototype;
            mini_ajax_cart.mini_cart_resize();
            setTimeout(mini_ajax_cart.mini_cart_resize, 200);
        });

        this.mini_cart_resize();

    },
    // captures heights of elements in mini cart
    mini_cart_resize: function() {
        var mini_cart_checkout_height = $j('.base_mini_cart_checkout_wrap').outerHeight();
        var mini_cart_title_height = $j('.base_mini_cart_title').outerHeight();
        var mini_cart_resize_height = mini_cart_checkout_height + mini_cart_title_height;
        $j('#minicart_list').css("height", 'calc(100% - ' + mini_cart_resize_height + 'px');
    },

    /**
     * Hang event listeners for ajaxCart
     */
    initCheckoutCartListeners: function() {
        //event listeners on edit
        var editLinks = [].slice.call($(this.ajaxCartItemsWrapper).getElementsByClassName(this.ajaxEditItemsClass));

        editLinks.each(function(editLink) {
            Event.observe(editLink, 'click', this._showEditForm.bindAsEventListener(this))
        }.bind(this));

        //event listeners on remove
        var removeLinks = [].slice.call($(this.ajaxCartItemsWrapper).getElementsByClassName(this.ajaxRemoveItemsClass));

        removeLinks.each(function(removeLink) {
            Event.observe(removeLink, 'click', this._deleteItem.bindAsEventListener(this))
        }.bind(this));
        //event listeners on estimator actions (estimate, update total)
        this._hangEventListenersOnEstimatorActions();
        //event listener on coupon
        this._hangEventListenerOnCoupon();
        //event listeners on wishlist
        this._hangEventListenerOnWishlist();
    },

    /**
     * Hang event listeners for minicart
     */
    initMinicartListeners: function() {
        //event listeners on edit
        var editLinks = [].slice.call($(this.miniCartItemsWrapper).getElementsByClassName(this.ajaxEditItemsClass));

        editLinks.each(function(editLink) {
            Event.observe(editLink, 'click', this._showEditForm.bindAsEventListener(this))
        }.bind(this));

        //event listeners on remove
        var removeLinks = [].slice.call($(this.miniCartItemsWrapper).getElementsByClassName(this.ajaxRemoveItemsClass));

        removeLinks.each(function(removeLink) {
            Event.observe(removeLink, 'click', this._deleteItem.bindAsEventListener(this))
        }.bind(this));

        //event listener on coupon
        this._hangEventListenerOnCoupon();
    },

    _hangEventListenersOnEstimatorActions: function() {
        //hang event listener on shipping estimator
        var estimatorForm = $(this.ajaxCartShippingZipForm);
        if(estimatorForm)
        {
            var shippingEstimatorButton = estimatorForm.down(this.ajaxCartShippingButtonClass);

            Event.observe(shippingEstimatorButton, 'click', this._submitShippingEstimatorBlock.bindAsEventListener(this));

            var shippingUpdateTotalButton = $(this.ajaxCartShippingWrapper).down(this.ajaxCartShippingTotalClass);

            if (shippingUpdateTotalButton) {
                Event.observe(shippingUpdateTotalButton, 'click', this._submitShippingUpdateTotal.bindAsEventListener(this));
            }
        }
    },

    _hangEventListenerOnCoupon: function() {
        //listener on 'apply' button
        var couponWrapperId = '';
        var couponFormId    = '';

        switch(this.type) {
            case this.ajaxCartType:
                couponWrapperId = this.tmAjaxCouponWrapperId;
                couponFormId    = this.ajaxCartCouponFormId;
                break;
            case this.minicartType:
                couponWrapperId = this.minicartCouponWrapperId;
                couponFormId    = this.minicartCouponFormId;
                break;
        }

        Event.observe($(couponFormId), 'submit', this._couponFormFireApplyClick.bindAsEventListener(this, couponFormId));
        Event.observe($(couponWrapperId).down(this.ajaxCartApplyCouponClass), 'click', this._submitCouponForm.bindAsEventListener(this));
        //listener on 'cancel' button
        var couponCancelLink = $$('#'+couponWrapperId+' '+this.ajaxCartCancelCouponClass);

        if (typeof couponCancelLink !== 'undefined') {
            couponCancelLink.each(function(link){
                Event.observe(link, 'click', this._cancelCoupon.bindAsEventListener(this));
            }.bind(this));
        }
        this.mini_cart_resize();
    },

    _couponFormFireApplyClick: function(event, couponFormId) {
        //prevent default
        Event.stop(event);
        var applyButton = $(couponFormId).down(this.ajaxCartApplyCouponClass);
        //fire click event
        applyButton.dispatchEvent(new Event('click'));
    },

    _hangEventListenerOnWishlist: function() {
        //event listeners on wishlist
        var wishlistLinks = [].slice.call($(this.ajaxCartItemsWrapper).getElementsByClassName(this.ajaxCartWishlistItemsClass));

        wishlistLinks.each(function(wishlistLink) {
            Event.observe(wishlistLink, 'click', this._wishlistItem.bindAsEventListener(this))
        }.bind(this));
    },

    /**
     * Show item edit form
     *
     * @param event
     * @private
     */
    _showEditForm: function(event) {
        //prevent default
        Event.stop(event);
        //set element in variable
        var element        = Event.element(event);
        var currentRow     = element.up(this.tmAjaxItemWrapperClass);
        var currentItemId  = currentRow.readAttribute('data-item-id');

        //hide actions & show edit form
        this._showArea(false, this._getItemActionsAreaByWrapperElement(currentRow));
        this._showArea(true, this._getItemFormAreaByWrapperElement(currentRow));
        //hang event listener on update/delete links
        this._hangListenerOnItemForm(this._getItemFormAreaByWrapperElement(currentRow));
    },

    /**
     * Hang event listener on form actions
     *
     * @param form {HTMLElement}
     * @private
     */
    _hangListenerOnItemForm: function(form) {
        //update
        Event.observe(form.down(this.tmAjaxItemFormUpdateClass), 'click', this._updateItem.bindAsEventListener(this));
        //cancel
        Event.observe(form.down(this.tmAjaxItemFormCancelClass), 'click', this._cancelUpdateItem.bindAsEventListener(this));
    },

    /**
     * Retrieve actions wrapper element
     *
     * @param element
     * @returns {HTMLElement}
     * @private
     */
    _getItemActionsAreaByWrapperElement: function(element) {
        return element.down(this.tmAjaxItemActionClass);
    },

    /**
     * Retrieve item form element
     *
     * @param element
     * @returns {HTMLElement}
     * @private
     */
    _getItemFormAreaByWrapperElement: function(element) {
        return element.down(this.tmAjaxItemFormClass);
    },

    _updateItem: function(event) {
        //prevent default
        Event.stop(event);
        //set element in variable
        var element         = Event.element(event);
        var currentForm     = element.up(this.tmAjaxItemFormClass);

        var itemForm = new VarienForm(currentForm.readAttribute('id'), true);
        if (itemForm.validator.validate()) {
            var form_fields = currentForm.serialize(true);
            new Ajax.Request(this.urls.update, {
                method: 'post',
                parameters: form_fields,
                onSuccess: this.itemOnSave,
                onLoading: this._ajaxLoader(true)
            });
        }
    },

    _deleteItem: function(event) {
        //prevent default
        Event.stop(event);
        //set element in variable
        var element     = Event.element(event);
        var currentRow  = element.up(this.tmAjaxItemWrapperClass);
        var currentForm = this._getItemFormAreaByWrapperElement(currentRow);

        var form_fields = currentForm.serialize(true);
        new Ajax.Request(this.urls.delete, {
            method: 'post',
            parameters: {id: form_fields.id},
            onSuccess: this.itemOnSave,
            onLoading: this._ajaxLoader(true)
        });
    },

    _wishlistItem: function(event) {
        //prevent default
        Event.stop(event);
        //set element in variable
        var element     = Event.element(event);
        var currentRow  = element.up(this.tmAjaxItemWrapperClass);
        var currentForm = this._getItemFormAreaByWrapperElement(currentRow);

        var form_fields = currentForm.serialize(true);
        new Ajax.Request(this.urls.wishlist, {
            method: 'post',
            parameters: {id: form_fields.id},
            onSuccess: this.itemOnSave,
            onLoading: this._ajaxLoader(true)
        });
    },

    _cancelUpdateItem: function(event) {
        //prevent default
        Event.stop(event);
        //set element in variable
        var element        = Event.element(event);
        var currentRow     = element.up(this.tmAjaxItemWrapperClass);

        //hide form & show actions
        this._showArea(false, this._getItemFormAreaByWrapperElement(currentRow));
        this._showArea(true, this._getItemActionsAreaByWrapperElement(currentRow));
    },

    _ajaxItemSuccess: function(response) {
        var responseData = response.responseText.evalJSON(true);
        if (responseData.success) {
            var total         = '';
            var itemsHtml     = '';
            var selectWrapper = '';
            //determine which totals we have in response
            switch(this.type) {
                case this.ajaxCartType:
                    total         = responseData.totals_html;
                    itemsHtml     = responseData.ajaxcart_list;
                    selectWrapper = this.ajaxCartSelectWrapperClass;
                    break;
                case this.minicartType:
                    total         = responseData.totals_html;
                    itemsHtml     = responseData.minicart_list;
                    selectWrapper = this.minicartSelectWrapperClass;
                    break;
            }

            this._showMessageSuccess(responseData.message);
            this._updateItemsHtml(itemsHtml);
            this._updateQty(responseData.quantitySummary);
            this._updateTotals(total);

            //init select2 plugin using wrapper class
            initSelect2(selectWrapper);

        } else {
            this._showMessageError(responseData.message);
        }

        this._ajaxLoader(false);
    },

    /**
     * Show/hide loaders
     *
     * @param action
     * @private
     * @return void
     */
    _ajaxLoader: function(action) {
        switch(this.type) {
            case  this.ajaxCartType:
                //use global quickview loader
                if (action) {
                    $(this.globalLoader).addClassName('active');
                } else {
                    $(this.globalLoader).removeClassName('active');
                }
                break;
            case this.minicartType:
                //use minicartLoader
                if (action) {
                    $(this.minicartLoader).show();
                } else {
                    $(this.minicartLoader).hide();
                }
                break;
        }
    },

    _updateItemsHtml: function(data) {
        switch(this.type) {
            case this.ajaxCartType:
                $(this.ajaxCartItemsWrapper).update(data);
                this.initCheckoutCartListeners();
                break;
            case this.minicartType:
                $(this.miniCartItemsWrapper).update(data);
                this.initMinicartListeners();
                break;
        }
    },

    _updateQty: function(data) {
        //my cart qty update on any page using any type
        $(this.myCartQty).update(data);

        switch(this.type) {
            case this.ajaxCartType:
                $(this.ajaxcartQty).update(data);
                break;
            case this.minicartType:
                $(this.minicartQty).update(data);
                break;
        }
    },

    _submitShippingEstimatorBlock: function(event) {
        //set element in variable
        var element         = Event.element(event);
        var estimatorForm   = element.up('#'+this.ajaxCartShippingZipForm);

        var estimatorVarienForm = new VarienForm(estimatorForm.readAttribute('id'), true);
        if (estimatorVarienForm.validator.validate()) {
            var form_fields = estimatorForm.serialize(true);
            new Ajax.Request(this.urls.estimator, {
                method: 'post',
                parameters: form_fields,
                onSuccess: this.estimatorOnSave,
                onLoading: this._ajaxLoader(true)
            });
        }

    },

    _submitCouponForm: function(event) {
        //set element in variable
        var element         = Event.element(event);
        var couponForm      = '';
        var coupon_code     = '';

        switch(this.type) {
            case this.ajaxCartType:
                couponForm      = element.up('#'+this.ajaxCartCouponFormId);
                coupon_code     = couponForm.down('#'+this.ajaxCartCouponCodeInputId);
                break;
            case this.minicartType:
                couponForm      = element.up('#'+this.minicartCouponFormId);
                coupon_code     = couponForm.down('#'+this.minicartCouponCodeInputId);
                break;
        }

        var couponVarienForm = new VarienForm(couponForm.readAttribute('id'), true);
        if (couponVarienForm.validator.validate()) {
            new Ajax.Request(this.urls.coupon, {
                method: 'post',
                parameters: {coupon_code: coupon_code.getValue(), apply: 1},
                onSuccess: this.couponOnApply,
                onLoading: this._ajaxLoader(true)
            });
        }
    },

    _cancelCoupon: function(event) {
        //prevent default
        Event.stop(event);
        var element              = Event.element(event);
        var appliedCouponWrapper = element.up('.applied_coupon_wrapper');

        new Ajax.Request(this.urls.coupon, {
            method: 'post',
            parameters: {coupon_code: appliedCouponWrapper.readAttribute('data-applied-coupon-code'), apply: 0},
            onSuccess: this.couponOnApply,
            onLoading: this._ajaxLoader(true)
        });
    },

    _submitShippingUpdateTotal: function(event) {
        //set element in variable
        var element              = Event.element(event);
        var shippingMethodForm   = element.up('#'+this.ajaxCartShippingMethodForm);

        var shippingMethodVarienForm = new VarienForm(shippingMethodForm.readAttribute('id'), true);
        if (shippingMethodVarienForm.validator.validate()) {
            var form_fields = shippingMethodForm.serialize(true);
            new Ajax.Request(this.urls.shipping_method, {
                method: 'post',
                parameters: form_fields,
                onSuccess: this.shippingMethodOnSave,
                onLoading: this._ajaxLoader(true)
            });
        }
    },

    _ajaxShippingEstimatorSuccess: function(response) {
        var responseData = response.responseText.evalJSON(true);

        if (responseData.success) {
            $(this.ajaxCartShippingWrapper).update(responseData.estimator_html);
            this._showMessageSuccess(responseData.message);
            this._hangEventListenersOnEstimatorActions();
            toggleShippinEstimator();
        } else {
            this._showMessageError(responseData.message);
        }

        this._ajaxLoader(false);
    },

    _ajaxShippingMethodSuccess: function(response) {
        var responseData = response.responseText.evalJSON(true);

        if (responseData.success) {
            this._updateTotals(responseData.totals_html);
            this._showMessageSuccess(responseData.message);
        } else {
            this._showMessageError(responseData.message);
        }

        this._ajaxLoader(false);
    },

    _ajaxCouponSuccess: function(response) {
        var responseData = response.responseText.evalJSON(true);

        var couponWrapperId = '';

        switch(this.type) {
            case this.ajaxCartType:
                couponWrapperId = this.tmAjaxCouponWrapperId;
                break;
            case this.minicartType:
                couponWrapperId = this.minicartCouponWrapperId;
                break;
        }

        if (responseData.success) {
            this._showMessageSuccess(responseData.message);
        } else {
            this._showMessageError(responseData.message);
        }

        if (responseData.couponExceeded) {
            this.showPopup(responseData.popupContent);
        }
        if(responseData.totals_html)
        {
            this._updateTotals(responseData.totals_html);
        }
        if(responseData.coupon)
        {
            $(couponWrapperId).update(responseData.coupon);
            this._hangEventListenerOnCoupon();
        }
        this._ajaxLoader(false);
    },

    /**
     * show default popup witrh conten
     * @param content
     */
    showPopup: function(content)
    {
        var popupContainer  = $(this.minicartPopupId);
        if(popupContainer) {
            popupContainer.update(content);
            showPopupCoupon(this.minicartPopupId);
        }
    },

    /**
     * Update totals html
     *
     * @param totals
     * @return void
     * @private
     */
    _updateTotals: function(totals) {
        switch(this.type) {
            case this.ajaxCartType:
                $(this.ajaxCartTotalsAreaId).update(totals);
                break;
            case this.minicartType:
                $(this.minicartTotals).update(totals);
                break;
        }
    },

    /**
     * Update minicart after quickbuy
     *
     * @param data
     */
    updateMinicart: function(data) {
        this._updateItemsHtml(data.minicart_list);
        this._updateQty(data.quantitySummary);
        this._updateTotals(data.totals_html);
        initSelect2(this.minicartSelectWrapperClass);
    },

    /**
     * Show success message
     *
     * @param message
     * @return void
     */
    _showMessageSuccess: function(message) {
        var area = this.ajaxCartMessagesArea;
        //determine which area use
        switch(this.type) {
            case this.ajaxCartType:
                area = this.ajaxCartMessagesArea;
                break;
            case this.minicartType:
                area = this.minicartMessagesArea;
        }

        $(area).show()
            .down('li').removeClassName('error-msg').addClassName('success-msg')
            .update(message);
        this._hideMessageTimeout();
    },

    /**
     * Show error message
     *
     * @param message
     * @return void
     */
    _showMessageError: function(message) {
        var area = this.ajaxCartMessagesArea;
        //determine which area use
        switch(this.type) {
            case this.ajaxCartType:
                area = this.ajaxCartMessagesArea;
                break;
            case this.minicartType:
                area = this.minicartMessagesArea;
        }

        $(area).show()
            .down('li').removeClassName('success-msg').addClassName('error-msg')
            .update(message);
        this._hideMessageTimeout();
    },

    /**
     * Hide message using timeout
     *
     * @return void
     * @private
     */
    _hideMessageTimeout: function() {
        var messageArea = '';

        switch(this.type) {
            case this.ajaxCartType:
                messageArea = this.ajaxCartMessagesArea;
                break;
            case this.minicartType:
                messageArea = this.minicartMessagesArea;
        }

        window.setTimeout(function () {
            $(messageArea).hide();
        }.bind(this), 5000);
    },

    /**
     * Show/hide element
     *
     * @param action boolean
     * @param element {HTMLElement}
     * @private
     */
    _showArea: function(action, element) {
        if (action) {
            //show
            $(element).show();
        } else {
            //hide
            $(element).hide();
        }
    },

    /**
     * Disable minicart animation (use only on ajaxcart type)
     *
     * @private
     * @return void
     */
    _minicartAnimationDisable: function() {
        $$('.open-panel').each(function(element){
            element.removeClassName('open-panel');
        });
    }
};

/** AJAX cart renderer composite design */
var TM_MinicartComposite = Class.create();
TM_MinicartComposite.prototype = {
    blocksMap: {},
    requestUrl: '',
    cartActionsUrls: {},
    cartType: 'minicart',
    preResponse: null,
    minicartSelectWrapperClass: 'base-mini-cart',

    initialize: function(configuration) {
        this.blocksMap = configuration.blocksMap;
        this.requestUrl = configuration.requestUrl;
        this.cartActionsUrls = configuration.cartActionsUrls;

        this._createDummyCartResponseObject();
        this._requestCart();
    },

    _createDummyCartResponseObject: function(){
        var self = this;
        window.TMMiniCart = {
            updateMinicart: function(response){
                self.preResponse = response;
            }
        };
    },

    _requestCart: function()
    {
        var request = new Ajax.Request(
            this.requestUrl,
            {
                method: 'post',
                parameters: this.blocksMap,
                onSuccess: this._renderCartInner.bind(this)
            }
        );
    },

    _renderCartInner: function(transport) {
        var updates = transport.responseJSON, element;
        for (id in updates) {
            element = $(id);
            if (!element) continue;
            element.update(updates[id]);
        }
        //minicart handling start
        var TMMiniCart = new TMAjaxCart(this.cartType, this.cartActionsUrls);
        initSelect2(TMMiniCart.minicartSelectWrapperClass);
        //moving pointer to global environment
        window.TMMiniCart = TMMiniCart;
        //rendering response in case if was requested earlier by quickbuy functionality
        if (this.preResponse) {
            TMMiniCart.updateMinicart(this.preResponse);
            this.preResponse = null;
        }

        //overlay close button handling
        $j('.base_mini_cart_close, .base_offCanvas_overlay').click(function(e){
            e.preventDefault();
            $j("body").removeClass("openNav");
            $j('.base_offCanvas_overlay').fadeOut(400);
        });
    }
};

添加优惠券后,我是否需要刷新?它显然是在听这个事件,但是没有刷新就没有填充它。如何通过ajax强制刷新?

0 个答案:

没有答案