Выводим AJAX-форму авторизации с обработкой ошибок без перезагрузки страницы и проверкой статуса пользователя.
Код |
---|
<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
// 1. Получаем URL авторизации через API Битрикс (без зависимости от $arResult)
$authUrl = $APPLICATION->GetCurPage(); // или '/auth/', если форма на отдельной странице
// 2. Проверяем, авторизован ли пользователь
if ($USER->IsAuthorized()):
?>
<div style="padding: 20px; background: #e8f5e9; border: 1px solid #a3e6a3;">
<p>Вы уже авторизованы как <strong><?= $USER->GetFullName() ?: $USER->GetLogin() ?></strong>.</p>
<a href="?logout=yes" style="color: #d9534f; text-decoration: none;">Выйти</a>
</div>
<?php
else:
?>
<div id="ajax-auth-container" style="max-width: 300px; margin: 20px auto; padding: 20px; border: 1px solid #ddd; border-radius: 8px;">
<h3 style="margin-top: 0;">Вход</h3>
<form id="ajax-auth-form" method="post" action="<?= $authUrl ?>" style="display: flex; flex-direction: column; gap: 10px;">
<input type="hidden" name="AUTH_FORM" value="Y" />
<input type="hidden" name="TYPE" value="AUTH" />
<input type="text" name="USER_LOGIN" placeholder="Логин" required style="padding: 8px;" />
<input type="password" name="USER_PASSWORD" placeholder="Пароль" required style="padding: 8px;" />
<button type="submit" style="padding: 10px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
Войти
</button>
<div id="auth-error" style="color: red; min-height: 20px;"></div>
</form>
<div style="margin-top: 15px; font-size: 14px;">
<a href="/auth/forgot/" style="color: #007bff; text-decoration: none;">Забыли пароль?</a> |
<a href="/auth/register/" style="color: #007bff; text-decoration: none;">Регистрация</a>
</div>
</div>
<script>
document.getElementById('ajax-auth-form').addEventListener('submit', function(e) {
e.preventDefault();
const form = this;
const formData = new FormData(form);
const errorDiv = document.getElementById('auth-error');
errorDiv.innerText = 'Отправка...';
fetch(form.action, {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(html => {
// Если в ответе есть элемент с ошибкой — покажем её
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const errorMsg = doc.querySelector('.errortext, .error, #auth-error');
if (errorMsg) {
errorDiv.innerText = errorMsg.innerText.trim() || 'Ошибка авторизации';
} else if (!html.includes('USER_LOGIN') && !html.includes('AUTH_FORM')) {
// Успешный вход — перезагружаем страницу
location.reload();
} else {
errorDiv.innerText = 'Неизвестная ошибка';
}
})
.catch(() => {
errorDiv.innerText = 'Ошибка соединения с сервером';
});
});
</script>
<?php endif; ?> |
Если вы хотите, чтобы форма обрабатывалась именно компонентом (например, для логирования, CAPTCHA, событий), — можно оставить IncludeComponent выше формы, но без вывода (скрыто), а форму оставить кастомной:
Код |
---|
<?php
// Скрытый вызов компонента — нужен для обработки POST-запроса
$APPLICATION->IncludeComponent("bitrix:system.auth.form", ".default", [], false);
?> |
Это обеспечит обработку логики авторизации, а визуальную часть вы контролируете сами.