Answer the question
In order to leave comments, you need to log in
Yii2 why modal window sends two requests?
Colleagues help with the problem!
The script of the bug is as follows, I click on the button that opens a modal window with an authorization form,
and it turns out that it immediately sends a post request, as soon as I filled in the fields without even clicking on the submit,
and if the fields remember some values, then I immediately get a login, I don’t do anything I understand the message Google rummaged through, not where I didn’t meet
this here is the code:
action controller
public function actionLogin()
{
if (Yii::$app->request->isAjax) {
$model = new LoginForm();
if ($model->load(Yii::$app->request->post())) {
if ($model->login()) {
return $this->goBack('/pizza');
} else {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
return $this->renderAjax('ajax-login', [
'model' => $model
]);
}
<a class="hidden-sm" id="modal-login-form" data-target="<?php echo \yii\helpers\Url::to('/user/ajax/login') ?>" title="Авторизация">
<span class="glyphicon glyphicon-log-in"></span> Вход
</a>
<?php
yii\bootstrap\Modal::begin([
'id' => 'modal',
'size' => 'modal-md',
]);
?>
<div id='modal-content'>Загружаю...</div>
<?php yii\bootstrap\Modal::end(); ?>
$('#modal-login-form').click(function () {
$('#modal').modal('show')
.find('#modal-content')
.load($(this).attr('data-target'));
return false;
});
<div class="login-popup">
<h1 class="modal-title"><?= Html::encode($this->title) ?></h1>
<div class="user-default-login">
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'enableAjaxValidation' => true,
'enableClientValidation' => true,
]); ?>
<?= $form->field($model, 'username')->textInput(['autocomplete' => 'off']) ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div style="color:#999;margin:1em 0">
<?= Html::a(Module::t('module', 'LINK_PASSWORD_RESET'), ['password-reset-request']) ?>.
</div>
<div class="form-group">
<?= Html::submitButton(Module::t('module', 'USER_BUTTON_LOGIN'), ['class' => 'btn btn-ma', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
Answer the question
In order to leave comments, you need to log in
As I understand it, the fault is .load($(this).attr('data-target'))
What 2 requests sends, you did not write.
You wrote in the body of the poll that it sends one request and immediately logs in.
Login immediately, because most likely, the event of submitting the form for validation is fired, and since the action is the same, it immediately logs in.
Everything works as coded)
js changes helped
$('#modal-login-form').on('click', function () {
$.get($(this).attr('data-target'))
.then(function (response) {
$('#modal').modal('show')
.find('#modal-content').html(response);
});
return false;
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question