konratnox
6/8/2017 - 9:20 AM

Неплохая форма с простенькой анимацией, проверкой на заполнение полей с рекапчей гугла 2

Неплохая форма с простенькой анимацией, проверкой на заполнение полей с рекапчей гугла 2

<? require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
define("STOP_STATISTICS", true);

if(CModule::IncludeModule("iblock")) {
    $result['status'] = 1;
    $IBLOCK_ID = 28;

    foreach ($_POST['data'] as $key => $value) {
        if (trim($value)) {
            $sendArray[$key] = htmlspecialcharsbx($value);
        } else {
            if(array_key_exists('form__'.$key, $_POST['requiredFields'])) {
                $result['status'] = 0;
                $result['errors']['form__'.$key] = 1;
                $result['message'] = '<p class="text-danger">Не все поля заполнены</p>';
            }
        }
    }

    $request = new \Bitrix\Main\Web\HttpClient(); //Создает объект HttpClient
    $post = $request->post("https://www.google.com/recaptcha/api/siteverify", Array(
        "secret" => "6LeCgSQUAAAAAHF6BpvTuJ4cbPxcUNCyvV6Osu5b", //здесь секретный ключ от Google
        "response" => $_POST["recaptcha"], //Сам хеш с формы
        "remoteip" => $_SERVER["REMOTE_ADDR"] //IP адрес пользователя проходящего проверку
    ));
    $post = json_decode($post); //Декодируем ответ от Google
    if($result['status']) {
        if($post->success == 'true') {

//            $text = '';
////            if($sendArray['name']) {
////                $text .= "Имя: ".$sendArray['name']."\n\r";
////            }
//            if($sendArray['message']) {
//                $text .= "Отзыв: ".$sendArray['message']."\n\r";
//            }
            if ($result['status'] != 0) {
                $el = new CIBlockElement;
                $arLoadProductArray = Array(
                    "IBLOCK_SECTION_ID" => false,
                    "IBLOCK_ID"      => $IBLOCK_ID,
                    "NAME"           => $sendArray['name'],
                    "ACTIVE"         => "N",
                    "PREVIEW_TEXT"   => $sendArray['message'],
                );
                $arFilesSend = array();
                if($reviewId = $el->Add($arLoadProductArray)) {
                    $reviews = array();
                    $db_props = CIBlockElement::GetProperty(12, $sendArray['product-id'], array('sort' => 'asc'), array('CODE' => 'REVIEWS'));
                    while($ar_props = $db_props->Fetch()){
                        $reviews[] = $ar_props['VALUE'];
                    }
                    $reviews[] = $reviewId;
                    CIBlockElement::SetPropertyValuesEx($sendArray['product-id'], 12, array('REVIEWS' => $reviews));
                    $result['status'] = 1;
                    $result['message'] = '<p class="text-success">Ваш отзыв отправлено!</p>';
                    CEvent::Send("PRODUCT_REVIEW", 's1', array("NAME"=>$sendArray['name'], "MESSAGE"=>$sendArray['message'], 'PRODUCT_NAME' => $sendArray['product-name']), 'Y', '37');
                } else {
                    $result['status'] = 0;
                    $result['message'] = '<p class="text-danger">Произошла ошибка! Попробуйте позже</p>';
                    $result['debag'] = $el->LAST_ERROR;
                }
            }
        } else {
            $result['message'] = '<p class="text-danger">Подтвердите, что вы не робот</p>';
            $result['status'] = 0;
        }
    }
    echo json_encode($result);
}
$(document).ready(function() {

    $('.contact-form__form').submit(function(event) {
        event.preventDefault();
        var $form = $(this);
        var requiredFields = $('.contact-form__form').find('.form__required').parent();
        var requiredFiledsId = {};
        requiredFields.each(function(index, el) {
            requiredFiledsId[$(el).attr('for')] = 1;
        });
        var data = {};
        var recaptcha = $('#g-recaptcha-response').val();
        data['name'] = $('#form__name').val();
        data['phone'] = $('#form__phone').val();
        data['phone'] = $('#form__phone').val();
        data['message'] = $('#form__message').val();
        data['product-id'] = $('#product-id').val();
        data['product-name'] = $('#product-name').val();
        $.ajax({
            url: '/ajax/reviewHandler.php',
            type: 'post',
            dataType: 'json',
            data: {data: data, requiredFields: requiredFiledsId, recaptcha: recaptcha},
        })
            .done(function(data) {
                if(data.status) {
                    $form.find('.form__error-message').html(data['message']);
                    grecaptcha.reset();
                    $form[0].reset();
                } else {
                    if(data['errors'] && Object.keys(data['errors']).length > 0) {
                        $form.addClass('form--animating');
                        for (var k in data['errors']) {
                            $('#' + k).addClass('form__error');
                        }
                    }
                    $form.find('.form__error-message').html(data['message']);
                    setTimeout(function () {
                        $form.removeClass('form--animating');
                        for (var k in data['errors']) {
                            $('#' + k).removeClass('form__error');
                        }
                        if($('#g-recaptcha-response').val() != '') {
                            grecaptcha.reset();
                        }
                    }, 800);
                }
            })
            .fail(function() {
            })
            .always(function() {
            });

    });
});

function recaptchaCallback () {
    $('.g-recaptcha').each(function() {
        var rc = grecaptcha.render(this, {
            'sitekey' : '6LeCgSQUAAAAAHS05utx4ZMEo5ikf00BtW9lWNRp'
        });

        $(this).find('iframe:first')
            .removeAttr('width')
            .removeAttr('height')
            .addClass('img-responsive')
            .parent()
            .parent()
            .css('width', 'auto');
    });
}
<div class="contact-form">
                    <form action="/ajax/sendForm.php" class="contact-form__form form form-horizontal col-xs-12">
                        <input type="hidden" id="product-id" name="product-id" value="<?=$arResult['ID']?>">
                        <input type="hidden" id="product-name" name="product-name" value="<?=$arResult['NAME']?>">
                        <div class="form-group">
                            <div class="col-xs-12 col-sm-offset-3 col-sm-6 col-md-5 form__error-message">

                            </div>
                        </div>
                        <div class="form-group">
                            <label for="form__name" class="col-xs-12 col-sm-3 control-label">Ваше имя <span class="form__required">*</span></label>
                            <div class="col-xs-12 col-sm-8 col-md-7">
                                <input name="name" type="text" class="form-control" id="form__name" placeholder="Ваше имя">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="form__message" class="col-xs-12 col-sm-3 control-label">Отзыв <span class="form__required">*</span></label>
                            <div class="col-xs-12 col-sm-8 col-md-7">
                                <textarea id="form__message" class="form__message form-control" name="message" placeholder="Отзыв"></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-xs-12 col-sm-3 control-label"></label>
                            <div class="col-xs-12 col-sm-9">
                                <div class="g-recaptcha"></div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-offset-3 col-sm-9 text-xs-center">
                                <button type="submit" class="btn btn-default contact-form__submit">Отправить письмо</button>
                            </div>
                        </div>
                    </form>
                </div>