Answer the question
In order to leave comments, you need to log in
Why doesn't validation work when submitting a form in Yii2 via ajax?
The situation is this. Created a form via ActiveRecord, it is sent via ajax (there is a JQuery handler). The problem is that there are required fields, without which the form should not be submitted. But with an ajax handler, it is sent anyway, and without it, everything works as expected.
Form code:
<?php $form = ActiveForm::begin([
'id' => 'write-review-form',
'action' => '/admin/send-mails/send-review',
]) ?>
<?= $form->field($review, 'firstname')->textInput(['placeholder' => 'Имя'])->label('') ?>
<?= $form->field($review, 'lastname')->textInput(['placeholder' => 'Фамилия (по желанию)'])->label('') ?>
<?php
$year = 1998;
$endYear = (int)date('Y');
$yearItems = [];
while ( $year <= $endYear ) {
$yearItems[$year] = $year;
$year += 1;
}
?>
<?= $form->field($review, 'since_year')->dropDownList($yearItems)->label('С какого года пользуетесь нашими услугами?') ?>
<?= $form->field($review, 'review')->textarea(['rows' => 5, 'placeholder' => 'Ваш отзыв'])->label('') ?>
<?= $form->field($review, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6" style="padding-top: 10px;">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-default send-review']) ?>
</div>
<?php ActiveForm::end(); ?>
$(function(){
var $form = $("#write-review-form");
$form.submit(submitForm);
function submitForm(e){
e.stopImmediatePropagation();
var $form = $(this),
$writeReview = $("#write-review");
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
dataType: 'json',
success: function(data){
console.log(data);
$writeReview.modal('hide');
}
});
return false;
}
});
Answer the question
In order to leave comments, you need to log in
To solve your problem, you need to use the beforeSubmit event, for example:
$("#write-review-form").on('beforeSubmit', function () {
return submitForm($(this));
});
function submitForm(form){
if (form.data("yiiActiveForm").validated == false ) {
return false;
}
// тут отправляем форму аяксом
}
Validation does not have time to work before you intercept the submission by the script and submit the form.
Therefore, either use the advice of Maxim Fedorov or use the built-in ajax method of validation and submission.
<?php $form = \yii\widgets\ActiveForm::begin([
'id' => 'my-form-id',
'action' => 'save-url',
'enableAjaxValidation' => true,
'validationUrl' => 'validation-rul',
]); ?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question