Easy way to make Ajax submit for the CActiveForm

Hello All

I have created the yii dialog with the CJuiDialog

And put it in the CActiveForm

Is there easy way to submit or validate the form with the Ajax?

Thank you much

This should be straight forward: http://www.yiiframework.com/doc/api/1.1/CActiveForm/

To enable ajax validation you can use a configuration like this




<?php $form = $this->beginWidget('CActiveForm', array(

    'id'=>'user-form',

    'enableAjaxValidation'=>true,

    'enableClientValidation'=>true,

    'focus'=>array($model,'firstName'),

)); ?>



and instead of using CHtml::submitButton you use CHtml::ajaxSubmitButton and put the corresponding logic to your controller action.

Thank you, Haensel

I was tried to add the button

but the button is working like the usual button,

but not the ajax




$form = $this->beginWidget('CActiveForm', array(

     'id'=>'user-form',

     'enableAjaxValidation'=>true,

     'enableClientValidation'=>false,

	 'clientOptions' => array('validationUrl' => Yii::app()->baseUrl.'/index.php/module/action/'),

     'focus'=>array($model,'name')

 ));


 echo $form->errorSummary($model); ?>


 <div class="row">

     <?php echo $form->labelEx($model,'parentName'); ?>

     <?php echo $form->textField($model,'parentName'); ?>

     <?php echo $form->error($model,'parentName'); ?>

 </div>

 <div class="row">

     <?php echo $form->labelEx($model,'name'); ?>

     <?php echo $form->textField($model,'name'); ?>

     <?php echo $form->error($model,'name'); ?>

 </div>

 

 <?

 

	echo CHtml::ajaxSubmitButton("submit", Yii::app()->baseUrl.'/index.php/module/action/', array('success' => 'function() { alert("12345"); } '), array('onclick' => 'alert("12345");') );

 

 ?>


 <?php $this->endWidget(); ?>



Is there any usefull method to do submit like the array buttons of the CJuiDialog




  'buttons'=> array('Ok' => 'js:function() { $("#user-form").submit(); alert("ok"); } ',

		    'Cancel' => 'js:function() { $("#mydialog").dialog( "close" ); } ')



At the moment I can see just the one suitable solution for me is the handler of the Ok button

for the dialog as the ajax request

Thank you for your time

You mean clicking the button causes a normal submit/page reload? That shouldn’t happen. Have you tried using it without specifying your own onclick event?

And by the way: I think you should use $this->createUrl(‘action’) instead of baseUrl.

try




        //$this is referring to the controller used. You can also use Yii::app()->controller->createUrl if that doesn't work

        echo CHtml::ajaxSubmitButton("submit", $this->createUrl('action'), array('success' => 'function() { alert("12345"); }'));



and use Firebug to log any ajax requests

Btw:: This wiki entry could be useful: You’ll have to take care of duplicate script downloads: http://www.yiiframework.com/wiki/72/cjuidialog-and-ajaxsubmitbutton

Thank you for your post!

But your solution does not work for me

  1. I have the page with the url - index.php/module/default/index

  2. Content of my popup is generated with the first request by the url - index.php/module/edit/ then

  3. The url - $this->createUrl(‘action’) still was the first my popup has been created

I am sorry but I don’t get what you mean with point 3 but if you mean that the url is wrong than maybe you should try adding the moduleId




$this->createUrl('module/controller/action');



Hello, Haensel

Week before I stopped the analysis of the ActiveForm and made the custom own ajax validator

But now I tried to fix the CActiveForm ajax submit and validation with the standard functionality.

You can reproduce the issue with the steps:

  1. You need to create the simple view first with the dialogue inside CJuiDialog

  2. Then you create the controller,

that will respond second view with the CActiveForm inside to the our dialogue created and CHtml::ajaxSubmitButton(“Submit”, ‘url’).

  1. Push the button "Submit".

The browser put you to the page ‘url’ in the same window but not send the ajax request.

I made some core code review and found that the problem is usual for Yii

Client side scripts not registered after the Ajax request.

When the button is initialized the CHtml::clientChange() is called but the scripts needed not executed




protected static function clientChange($event,&$htmlOptions)

{

...


    $cs=Yii::app()->getClientScript();

    $cs->registerCoreScript('jquery');


    if(isset($htmlOptions['submit']))

    {

        $cs->registerCoreScript('yii');

        $request=Yii::app()->getRequest();

        if($request->enableCsrfValidation && isset($htmlOptions['csrf']) && $htmlOptions['csrf'])

            $htmlOptions['params'][$request->csrfTokenName]=$request->getCsrfToken();

        if(isset($htmlOptions['params']))

            $params=CJavaScript::encode($htmlOptions['params']);

        else

            $params='{}';

        if($htmlOptions['submit']!=='')

            $url=CJavaScript::quote(self::normalizeUrl($htmlOptions['submit']));

        else

            $url='';

        $handler.="jQuery.yii.submitForm(this,'$url',$params);{$return};";

    }


    if(isset($htmlOptions['ajax']))

        $handler.=self::ajax($htmlOptions['ajax'])."{$return};";


    if(isset($htmlOptions['confirm']))

    {

        $confirm='confirm(\''.CJavaScript::quote($htmlOptions['confirm']).'\')';

        if($handler!=='')

            $handler="if($confirm) {".$handler."} else return false;";

        else

            $handler="return $confirm;";

    }


    if($live)

        $cs->registerScript('Yii.CHtml.#'.$id,"jQuery('body').undelegate('#$id','$event').delegate('#$id','$event',function(){{$handler}});");

    else

        $cs->registerScript('Yii.CHtml.#'.$id,"jQuery('#$id').unbind('$event').bind('$event', function(){{$handler}});");

    ...

}



So at the moment (current version) I could not solve the Validation in my pop-up window regularly .

But everything is fine when the form is "on the ground" (first view renders the form)

I’ve found the simple and easy way howto fix the problem.

The problem was because by default CClientScript::renderOutput is not called with the CController::renderPartial();

You need to send response with client scripts CController::renderPartial(‘module.views.myview’, array(‘model’=>$model), false, [color="#FF0000"]true[/color]);

You can add any own script to the view now.

Yii::app()->getClientScript()->registerScript("InitDivisionTree", $scriptBody);

Exclude jquery from the registeredScripts or don’t forget to make your own jquery components initialization

after the ajax view is rendered - because of the jquery is called twice when you don’t create it.

Please, also check the topic of the CClientScript::registerClientScript (http://www.yiiframework.com/forum/index.php?/forum/29-general-discussion-for-yii-11x/) problem