Yii2 form event-Ajax submission implementation method, yii2 form ajax submission
This article describes how to implement Ajax submission for Yii2 form events. We will share this with you for your reference. The details are as follows:
Preface
Yii2 now uses JavaScript to register code.
There are two methods to implement Ajax submission. First, the beforeSubmit parameter is called directly in ActiveForm, but I personally think that JS and HTML are not well separated. Therefore, this article mainly introduces the second method-External writing JS method.
Form part
<?php $form = ActiveForm::begin([ 'id' => $model->formName(), 'action' => ['/apitools/default/index']]); ?>
Ajax
<?php$js = <<<JS// get the form id and set the event$('form#{$model->formName()}').on('beforeSubmit', function(e) { var \$form = $(this); // do whatever here, see the parameter \$form? is a jQuery Element to your form}).on('submit', function(e){ e.preventDefault();});JS;$this->registerJs($js);
If you use JsBlock, you can write as follows:
<?php JsBlock::begin() ?> <script> $(function () { jQuery('form#apitool').on('beforeSubmit', function (e) { var $form = $(this); $.ajax({ url: $form.attr('action'), type: 'post', data: $form.serialize(), success: function (data) { // do something } }); }).on('submit', function (e) { e.preventDefault(); }); </script><?php JsBlock::end() ?>