Loremipsumdolorsit
9/12/2017 - 8:32 AM

ajax subscription template for main page (can be used in footer, for example)

ajax subscription template for main page (can be used in footer, for example)

<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
use Bitrix\Main\Localization\Loc;?>

<?
	/*т.к. в верстке не предусмотрен выбор рубрики 
	 * на которую пользователь желает подписатся,
	 * подписка будет осуществлятся на рубрику с ИД = 1*/
?>

<?
	if(!empty($arResult["ERROR"]) && $_REQUEST['ajax'] == 'Y'){
        $APPLICATION->RestartBuffer();
        echo json_encode(['status' => 'error', 'mess' => GetMessage('error_occurred')]);
        die;
    }
?>

<?
//whether to show the forms
if($arResult["ID"] == 0 && empty($_REQUEST["action"]) || CSubscription::IsAuthorized($arResult["ID"]))
{
	//status and unsubscription/activation section
	if($arResult["ID"]>0)
	{
		include("status.php");

		if($_REQUEST['ajax'] == 'Y'){
            $APPLICATION->RestartBuffer();
            ob_start();
            include("status.php");
            $html = ob_get_contents();
            ob_clean();
            echo json_encode(['status' => 'ok', 'html' => $html]);
            die;
        }

	}else{
		//setting section
		include("setting.php");
	}
}
?>
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
<?
//***********************************
//status and unsubscription/activation section
//***********************************
?>
		<form action="<?=$arResult["FORM_ACTION"]?>" method="get" id="subscription-list">
			<?echo bitrix_sessid_post();?>
			<input type="hidden" name="ID" value="<?echo $arResult["SUBSCRIPTION"]["ID"];?>" />
			<table class="lk-subscribe__table">
                <tbody>
                    <?if($arResult["SUBSCRIPTION"]["CONFIRMED"] <> "Y"):?>
                        <tr class="lk-subscribe__table--output">
							<td>
								<span><?echo GetMessage("subscr_title_status_note1")?></span>
							</td>
                        </tr>
                    <?elseif($arResult["SUBSCRIPTION"]["ACTIVE"] == "Y"):?>
                        <tr class="lk-subscribe__table--output">
							<td>
								<span><?echo GetMessage("subscr_title_status_note2")?></span>
                                <a href="javascript:void(0);" class="bold-text"><?=$arResult['SUBSCRIPTION']['EMAIL']?></a>
							</td>
                        </tr>
                        <tr class="lk-subscribe__table--output">
							<td>
                                <a class="btn btn-normal btn-hover-normal btn-inverse subscribe-submit">
                                    <?echo GetMessage("subscr_unsubscr")?>
                                </a>
                                <input type="hidden" name="unsubscribe" value="Y"/>
                                <input type="hidden" name="action" value="unsubscribe" />
	                        </td>
                        </tr>
                    <?else:?>
                        <tr class="lk-subscribe__table--output">
							<td>
								<span><?echo GetMessage("subscr_status_note4")?></span>
								<span><?echo GetMessage("subscr_status_note5")?></span>
							</td>
                        </tr>
                        <tr class="lk-subscribe__table--output">
							<td>
                                <a class="btn btn-normal btn-hover-normal btn-inverse subscribe-submit">
                                    <?echo GetMessage("subscr_activate")?>
                                </a>
	                        	<input type="hidden" name="activate"value="Y"/>
								<input type="hidden" name="action" value="activate" />
	                        </td>
                        </tr>
                    <?endif;?>
                </tbody>
            </table>
		</form>
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>
<?
//***********************************
//setting section
//***********************************
?>

<form action="<?=$arResult["FORM_ACTION"]?>" method="post">
    <?echo bitrix_sessid_post();?>
    <input type="hidden" name="RUB_ID[]" value="<?=DEFAULT_MAILING_ID?>"/>
    <input type="hidden" name="FORMAT" value="text" />
    <input type="hidden" name="PostAction" value="<?echo ($arResult["ID"]>0? "Update":"Add")?>" />
    <input type="hidden" name="ID" value="<?echo $arResult["SUBSCRIPTION"]["ID"];?>" />
    <input type="hidden" name="Save" value="Y"/>

    <fieldset class="custom-input custom-input--gray">
        <label for="f-1">Ваше имя</label>
        <input type="text"
               id="f-1"
               placeholder="Введите ваше имя">
    </fieldset>
    <fieldset class="custom-input custom-input--gray">
        <label for="f-2">E-mail</label>
        <input type="email"
               name="EMAIL"
               id="f-2"
               value="<?=$arResult["SUBSCRIPTION"]["EMAIL"]!=""?$arResult["SUBSCRIPTION"]["EMAIL"]:$arResult["REQUEST"]["EMAIL"];?>"
               placeholder="Введите ваш электронный адрес">
    </fieldset>
    <fieldset>
        <input type="submit"
               class="uk-hidden"
               value="Подписаться"
               name="Save">
    </fieldset>
    <a href="javascript:void(0);"
       role="button"
       class="btn btn-normal btn-hover-normal btn-inverse subscribe-submit">Подписаться</a>
</form>
(function (Webvision) {
    window.Webvision = Webvision = Webvision || {};

    $.extend(Webvision, {
        //constants
        ajaxDir : '/ajax/common.php',
        phoneMask: '+38(999) 999-99-99',

        // global selectors
        selectors : {

        },
        
        consts : {
            confirmSubscrMess: {
            	ru : 'Подтвердике подписку по email',
				ua : 'Підтвердіть підписку по email',
				en : 'Confirm subscription by email'
			},
            goToSubscrMess: {
                ru : 'Перейти к подпискам',
                ua : 'Перейти до підписок',
                en : 'Go to subscriptions'
			},
        },
        
        //functions
        serializeObject: function(){
            $.fn.serializeObject = function()
            {
                var o = {};
                var a = this.serializeArray();
                $.each(a, function() {
                    if (o[this.name] !== undefined) {
                        if (!o[this.name].push) {
                            o[this.name] = [o[this.name]];
                        }
                        o[this.name].push(this.value || '');
                    } else {
                        o[this.name] = this.value || '';
                    }
                });
                return o;
            };
        },
        
        events: function(){
        	var _this = this;

        	if(location.pathname == '/index.php' || location.pathname == '/'){
                $(document).on('click', '.subscribe-submit', function(){
					var $form = $(this).closest('form');

                    $.post(
                        $form.attr('action'),
                        $.extend($form.serializeObject(), {ajax : 'Y'}),
                        function(response){
							if(response.status){
                                switch (response.status) {
                                    case 'ok':
										$form.replaceWith(response.html);
                                        break;
                                    case 'error':
                                        $form.prepend('<p>' + response.mess + '</p>');
                                        break;
                                    default:
                                        break;
                                }

							}
                        },
						'json'
                    );
                });
			}
        },

        getQueryParams: function(qs) {
            qs = qs.split('+').join(' ');

            var params = {},
                tokens,
                re = /[?&]?([^=]+)=([^&]*)/g;

            while (tokens = re.exec(qs)) {
                params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
            }

            return params;
        },
        
        setPhoneMask: function() {
            $('input[type=tel]').mask(Webvision.phoneMask);
        },
	    
	    checkForm: function(form){
	    	
	    	var result = true,
	    		_this = Webvision,
	    		regEl = $(form).find('.required:visible'),
	    		emails = $(form).find('input[data-type=email]');
	    	
	    	regEl.each(function(idx, el){
	    		if(el.value.trim() == ''){
	    			$(this).addClass('empty-input');
	    		}else{
	    			$(this).removeClass('empty-input');
	    		}
	    	});
	    	
	    	emails.each(function(idx, el){
	    		if(!_this.checkEmail(el.value.trim(), $(this))){
	    			$(this).addClass('empty-input');
	    		}else{
	    			$(this).removeClass('empty-input');
	    		}
	    	});
	    	
	    	if($(form).find('.empty-input:visible').length > 0){
	    		result = false;
	    	}
	    	
	    	return result;
	    },
	    
	    checkEmail: function(emailAddress, $input) {
	  	  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
	  	  	  errmess = 'Email адрес должен содержать символ @ и .',
	  	  	  res = re.test(emailAddress);

	  	  $input.parent().find('.error-mail').remove();
	  	  if(!res){
	  		  if($input.next().is('label'))
	  			  $input.next().after('<p class="error-mail">'+errmess+'</p>');
	  		  else
	  			$input.after('<p class="error-mail">'+errmess+'</p>');
	  	  }
	  	  
	  	  return res;
	  	},
	  	
	  	updateSmallBasket: function(){
	  		var _this = Webvision,
	  			data = {
	  				'handler' : 'basket',
	  				'func' : 'getSmallBasketHTML'
	  			};
	  		
	  		var callback = function(response){
	  			if(response.status && response.status == 'ok'){
	  				$(_this.selectors.smallBasketWrapper).html(response.data.html);
	  			}
	  		};
	  		
	  		$.post(
	  			_this.ajaxDir,
	  			data,
	  			callback,
	  			'json'
	  		);
	  	},
        
	    init: function () {
            Webvision.serializeObject();
            Webvision.events();
        }
    });

})(window.Webvision);



$(document).ready(function () {
    Webvision.init();
});