Ajax form submiting in Yii

You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#3)next (#5) »

  1. PersonForm model
  2. person_form.php
  3. PersonController.php

hi guys, Here I'm going to give you a working example of ajax form submiting in Yii.

You can try a simple demo here:DEMO

Find the source code @https://github.com/sirinibin/yiidemos

PersonForm model

<?php

class PersonForm extends CFormModel
{

 	public $name;
        public $age;

	/**
	 * Declares the validation rules.
	 * title is required
	 */
	public function rules()
	{
		return array(
			
		       );
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'name'=>'Name',
                        'age'=>'Age',
		);
	}
 
}

?>

form:

person_form.php

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'person-form-edit_person-form',
	'enableAjaxValidation'=>false,
        'htmlOptions'=>array(
                               'onsubmit'=>"return false;",/* Disable normal form submit */
                               'onkeypress'=>" if(event.keyCode == 13){ send(); } " /* Do ajax call when user presses enter key */
                             ),
)); ?>

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

	<div class="row">
		<?php echo $form->labelEx($model,'name'); ?>
		<?php echo $form->textField($model,'name'); ?>
		<?php echo $form->error($model,'name'); ?>
	</div>
        <div class="row">
		<?php echo $form->labelEx($model,'age'); ?>
		<?php echo $form->textField($model,'age'); ?>
		<?php echo $form->error($model,'age'); ?>
	</div>


	<div class="row buttons">
	    <?php echo CHtml::Button('SUBMIT',array('onclick'=>'send();')); ?> 
	</div>

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

</div><!-- form -->
<script type="text/javascript">

function send()
 {
   
   var data=$("#person-form-edit_person-form").serialize();


  $.ajax({
   type: 'POST',
    url: '<?php echo Yii::app()->createAbsoluteUrl("person/ajax"); ?>',
   data:data,
success:function(data){
                alert(data); 
              },
   error: function(data) { // if error occured
         alert("Error occured.please try again");
         alert(data);
    },

  dataType:'html'
  });

}

</script>

Controller:

PersonController.php

class PersonController extends CController
{
 public function actionAjax()
 {
    $model=new PersonForm;

    // uncomment the following code to enable ajax-based validation
    /*
    if(isset($_POST['ajax']) && $_POST['ajax']==='person-form-edit_person-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
    */


    if(isset($_POST['PersonForm']))
    {
       
          
        $model->attributes=$_POST['PersonForm'];
        if($model->validate())
        {
           // form inputs are valid, do something here
           print_r($_REQUEST);
           return;
                    
        
         
        }
    }
    $this->render('person_form',array('model'=>$model));

 }

In the above example you will get an alert on the javascript ajax callback function which will be a server response from the controller action.You can customise this code as per your needs.i hope this will help someone.Thanks

-Sirin Hire Yii developer