yii CActiveForm submitting by AJAX

yii
14,628

Solution 1

This helper ajaxSubmitButton function isn't terribly useful, especially since it uses jquery.ajax() without using the "Promise interface" in jquery 1.5+, so you have to process the response through the success callback. This would have been cleaner if they just used jquery.submit(). You're better off just rolling your own, honestly.

I'm disappointed that none of the (relatively popular) Bootstrap integrations like Yii-Bootstrap or YiiBooster offer much of anything in terms of generating forms that refresh themselves with ajax response data either (I'm not talking validation). I go through all the trouble of learning & adopting a framework, only to end up html/js/css-coding my own frontend presentation and logic anyway... Oh well.

I'm still a Yii enthusiast, mostly due to their gii generator and support for quasi-mixin patterns with "behaviors". It leads to clean code on the backend, but the framework has some growing to do on the frontend & view rendering. Their "CHtml" library really isn't cutting it right now.

Solution 2

One way to do this is to use the built in ajaxSubmitButton helper, like so:

<?php $form=$this->beginWidget('CActiveForm', array(
  'id'=>'contacts-form',
  'enableAjaxValidation'=>false,
)); ?>
<!-- your form elements here -->
<?php echo CHtml::ajaxSubmitButton(Yii::t('app', 'Submit')); ?>
<?php $this->endWidget(); ?>

This automatically binds a jQuery AJAX call to the SUbmit button which will POST the form values to your from's action URL.

You could also write the AJAX code yourself, of course, but Yii has this helper function too.

Share:
14,628
Shahid Karimi
Author by

Shahid Karimi

Passionate, enthusiast IT professional in true spirit!

Updated on June 04, 2022

Comments

  • Shahid Karimi
    Shahid Karimi almost 2 years

    I create form using the following code:

    <?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'contacts-form',
        'enableAjaxValidation'=>false,
    
    )); ?>
    

    Is there any way to submit the form by AJAX? Remember not I am not talking about AJAX validation.