Yii2 form event-Ajax submission implementation method, yii2 form ajax submission

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.