C
C
Crash2016-11-01 13:56:22
Yii
Crash, 2016-11-01 13:56:22

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(); ?>


Handler code:
$(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;
    }
});


What can be wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-11-01
@Bandicoot

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;
    }
   // тут отправляем форму аяксом
}

But it is worth remembering that in the case of submitting the form by Yax, only client validation will be processed (if it is enabled), and you will have to process server validation yourself

M
Maxim Timofeev, 2016-11-01
@webinar

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',
]); ?>

D
Dmitry, 2016-11-01
@slo_nik

Good afternoon.
Maybe this video will help you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question