Apply coupon using ajax

Right now when I click on a apply coupon code button the whole page will be refreshed, this can't be done with AJAX?

  • Nahid

    Hey Jing !
    Hope you are having a great day!

    This request has been escalated to our Second Level Support team. They'll be back to us with clues, workarounds, and fixes (if possible) for now in this ticket (or we'll be updating the ticket as soon as we hear back from them internally). Please note that the response time of the Second Level Support team might be a bit delayed than that of the general Support staff. We really appreciate your patience and consideration regarding this. Moreover, as this is a custom request, we cannot assure a workaround from our end just yet without investigation. This might get flagged as a feature request or you might need to consider custom development if this turns out to be undoable from our end. We really appreciate your patience and consideration regarding this.

    Kind regards,
    Nahid

  • Panos

    Hi there Jing ,

    It is possible but this is not in the plugin designs. It requires some custom code and tweaks so it exceeds the scope of support. For this you would probably need to hire a developer.

    Having this said, I have prepared a custom snippet which you can add in a mu-plugin and try it out.

    It is more likely it does not cover all your needs or it will need some sort of changes. As I said already though, we can't support those, so you can use the following as a guide only and not as a complete solution:

    function wpmudev_ms_set_coupon_ajax() {
    
    	check_ajax_referer( 'wpmudev_ms_set_coupon', 'security' );
    
    	if ( ! isset( $_POST['ms_relationship_id'] ) ) {
    		$return = array(
                'success'       =>  false,
                'content'       =>  "Parameters are missing"
            );
            wp_send_json($return);
    	}
    
    	$code 			= filter_input( INPUT_POST, 'coupon_code', FILTER_DEFAULT );
    	$data 			= array();
    	$subscription 	= null;
    	$member 		= MS_Model_Member::get_current_member();
    	$membership_id 	= 0;	
    
    	if ( empty( $code ) ) {
    		$return = array(
                'success'       =>  false,
                'content'       =>  '<p class="ms-alert-box ms-alert-error"> Coupon code not found.</p>'
            );
            wp_send_json($return);
    	}
    
    	$coupon 		= MS_Addon_Coupon_Model::load_by_code( $code );
    
    	if ( ! $coupon || ! $coupon->is_valid( $membership->id ) ) {
    		$return = array(
                'success'       =>  false,
                'content'       =>  '<p class="ms-alert-box ms-alert-error"> Coupon code not found.</p>'
            );
            wp_send_json($return);
    	}
    
    	$coupon_addon = new MS_Addon_Coupon();
    
    	$subscription = MS_Factory::load(
    		'MS_Model_Relationship',
    		absint( intval( $_POST['ms_relationship_id'] ) )
    	);
    	$membership 	= $subscription->get_membership();
    	$membership_id 	= $membership->id;
    	$invoice 		= $subscription->get_current_invoice();	
    
    	if ( $_invoice = $coupon_addon->apply_discount( $invoice, $subscription ) ) {
    		$_invoice->save();
    
    		ob_start();
    		?>
    		<tr class="ms-invitation-code">
    			<td colspan="2">
    				<div class="membership-coupon">
    					<div class="membership_coupon_form couponbar">
    						<form method="post">
    							<div class="coupon-entry">
    								<input class="wpmui-field-input wpmui-hidden " type="hidden" id="coupon_code" name="coupon_code" value="<?php echo $coupon->code; ?>">
    								<label for="remove_coupon_code" class="wpmui-field-label  wpmui-label-remove_coupon_code inline-label">
    									Coupon applied: <?php echo $coupon->code; ?>
    								</label>
    
    								<button class="wpmui-field-input button  wpmui-submit button-primary" type="submit" id="remove_coupon_code" name="remove_coupon_code" value="1">
    									Remove
    								</button>
    
    								<input class="wpmui-field-input wpmui-hidden " type="hidden" id="membership_id" name="membership_id" value="<?php echo $membership_id; ?>">
    
    								<input class="wpmui-field-input wpmui-hidden " type="hidden" id="move_from_id" name="move_from_id" value="0">
    								<input class="wpmui-field-input wpmui-hidden " type="hidden" id="step" name="step" value="payment_table">
    							</div>
    						</form>
    					</div>
    				</div>
    			</td>
    		</tr>
    		<?php
    		$remove_button = ob_get_clean();
    
    		ob_start();
    		?>
    		<tr>
    			<td class="ms-title-column"> Price</td>
    			<td class="ms-details-column"> <span class="price"> <?php echo MS_Helper_Billing::format_price( $invoice->total ); ?> </span></td>
    		</tr>
    		<tr>
    			<td class="ms-title-column"> Coupon Discount</td>
    			<td class="ms-price-column"> <?php echo MS_Helper_Billing::format_price( $_invoice->discount ); ?></td>
    		</tr>
    		<?php
    		$discount_row = ob_get_clean();
    
    		$return = array(
                'success'       	=> true,
                'content'       	=> "Coupon set",
                'invoice_total' 	=> MS_Helper_Billing::format_price( $_invoice->total ),
                'invoice_discount' 	=> $_invoice->discount,
                'remove_button'		=> $remove_button,
                'discount_row' 		=> $discount_row
            );
            wp_send_json($return);
    	}
    
    }
    
    add_action( 'wp_ajax_wpmudev_ms_set_coupon', 'wpmudev_ms_set_coupon_ajax', 10 );
    add_action( 'wp_ajax_nopriv_wpmudev_ms_set_coupon', 'wpmudev_ms_set_coupon_ajax', 10 );
    
    add_action( 'ms_view_frontend_payment_after_total_row', function(){
    	add_action( 'wp_footer', 'wpmudev_ms_ajax_coupon_view', 20 );
    }, 20 );
    
    function wpmudev_ms_ajax_coupon_view(){
    
    	?>
    	<script type="text/javascript">
    		(function($){
    			$(document).ready(function(){
    				$('#apply_coupon_code').on('click', function(e){
    					e.preventDefault();
    
    					var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>',
    						data = {
    	                        action: 'wpmudev_ms_set_coupon',
    	                        security: '<?php echo wp_create_nonce( "wpmudev_ms_set_coupon" ); ?>',
    	                        ms_relationship_id: $('#ms_relationship_id').val(),
    	                        coupon_code: $('#coupon_code').val(),
    	                        apply_coupon_code: true
    	                    };
    
                        $.post(ajaxurl, data, function( response ) {
    
                        	$('.ms-invitation-code form .ms-alert-error').remove();
    
                            if( response.success ){
                            	// 1. Set new total:
                            	$( '.ms-total .price' ).html( response.invoice_total );
                            	// 2. Add remove button:
                            	//$( '.ms-purchase-table' ).append( response.remove_button )
                            	$( 'table.ms-purchase-table tr' ).eq(1).after( response.remove_button );
                            	// 3. Insert the discount amount row
                            	$( 'table.ms-purchase-table tr:first' ).after( response.discount_row );
                            	// 4. Replace price in subscription description
                            	$( '.ms-membership-description .price' ).html( response.invoice_total );
                            }
                            else{
                            	$('.ms-invitation-code form').prepend( response.content );
                            }
    
                        });
    
    				});
    			});
    		})(jQuery);
    	</script>
    	<?php
    }

    Hope this helps!

    Kind regards!

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.