javascript - Yii2 activeform ajax submit and validation -


currently achieve ajax submit , validation @ 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 php side, validation config looks that:

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

i'm sure it's not best way achieve need. part use preventing submission in case of validation error:

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

any suggestions? how achieve ajax submission , validation using yii 2's inbuilt settings?

use beforesubmit event instead of submit, beforesubmit triggered once form passes 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(); }); 

Comments