Stanimir Stoyanov Stanimir Stoyanov - 6 months ago 26
PHP Question

Yii2 active form, please wait message while submitting with ajax

I'm using Yii2's advanced template, and looking for a way to display a dialog with 'Please wait...' message while sending an login form to the server.

Here is my active form code:

<?php $form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => true,
]); ?>
<fieldset>

<?= $form->field($model, 'username', [
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('username'),
],
])->label(false); ?>

<?= $form->field($model, 'password', [
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('password'),
],
])->label(false)->passwordInput() ?>

<?= $form->field($model, 'rememberMe')->checkbox() ?>

<?= Html::submitButton('Login', ['class' => 'btn btn-lg btn-success btn-block', 'name' => 'login-button']) ?>
</fieldset>
<?php ActiveForm::end(); ?>


And my server side action:

public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}

$model = new LoginForm();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}


I'm successfully validating the inputs / sending the form, but need to display a dialog, so if the connection is slow the user will get an idea that the form is actually sending and needs more time to complete.

Answer

For ActiveForm you need to use according events. Currently it's managed with Javascript (see official upgrade info).

$('#myform').on('ajaxBeforeSend', function (event, jqXHR, settings) {
    // Activate waiting label
}).on('ajaxComplete', function (event, jqXHR, textStatus) {
    // Deactivate waiting label
});

Here is more detailed info about these two events.

ajaxBeforeSend:

ajaxBeforeSend event is triggered before sending an AJAX request for AJAX-based validation.

The signature of the event handler should be:

function (event, jqXHR, settings)

where

  • event: an Event object.

  • jqXHR: a jqXHR object

  • settings: the settings for the AJAX request

ajaxComplete:

ajaxComplete event is triggered after completing an AJAX request for AJAX-based validation. The signature of the event handler should be:

function (event, jqXHR, textStatus)

where

  • event: an Event object.

  • jqXHR: a jqXHR object

  • textStatus: the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

Also check this extension, maybe it will be useful for this purpose.

Comments