Yii2 activeform ajax submit and validation

heron picture heron · Jul 14, 2015 · Viewed 23.8k times · Source

Currently to achieve ajax submit and validation at the same time. I'm using custom function like:

    $('.edit_form').submit(function (e) {
        e.preventDefault();
        var form = $(this);
        var formData = $(this).serialize();
        if (form.find('.has-error').length) {
            return false;
        }

        $.ajax({
            url: form.attr("action"),
            type: form.attr("method"),
            data: formData,
            success: function (data) {
                 ...
            },
            error: function () {
                alert("Something went wrong");
            }
        });

    });

And here is php side, for validation my config looks like that:

$form = ActiveForm::begin([
    'id' => "some_form",
    'action' => ['user/edit'],
    'options' => ['class' => 'edit_form'],
    'enableAjaxValidation' => false,
    'enableClientValidation' => true,
]); ?>

I'm sure that It's not the best way to achieve what I need. Especially this part that I use for preventing for submission in case of validation error:

    if (form.find('.has-error').length) {
        return false;
    }

Any suggestions? How to achieve ajax submission and validation properly using Yii 2's inbuilt settings?

Answer

Nader picture Nader · Dec 1, 2015

Use beforeSubmit event instead of submit, the beforeSubmit will only be triggered once the form passes the validation.

$('form').on('beforeSubmit', function(e) {
    var form = $(this);
    var formData = form.serialize();
    $.ajax({
        url: form.attr("action"),
        type: form.attr("method"),
        data: formData,
        success: function (data) {
             ...
        },
        error: function () {
            alert("Something went wrong");
        }
    });
}).on('submit', function(e){
    e.preventDefault();
});