Yii 1.1: Ajax form submiting in Yii


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

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(



<div class="form">
<?php $form=$this->beginWidget('CActiveForm', 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 class="row">
        <?php echo $form->labelEx($model,'age'); ?>
        <?php echo $form->textField($model,'age'); ?>
        <?php echo $form->error($model,'age'); ?>
    <div class="row buttons">
        <?php echo CHtml::Button('SUBMIT',array('onclick'=>'send();')); ?> 
<?php $this->endWidget(); ?>
</div><!-- form -->
<script type="text/javascript">
function send()
   var data=$("#person-form-edit_person-form").serialize();
   type: 'POST',
    url: '<?php echo Yii::app()->createAbsoluteUrl("person/ajax"); ?>',
   error: function(data) { // if error occured
         alert("Error occured.please try again");



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);
           // form inputs are valid, do something here

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


Total 8 comments

#18585 report it
vijay p s at 2014/11/22 06:29am
var data=$("#person-form-edit_person-form").serialize();

How can pass the value to form id Dynamically using loop.

#16692 report it
Ben Bi at 2014/03/19 10:35pm
Not really work
'onkeypress'=>" if(event.keyCode == 13){ send(); } "

This part is trouble, imagine u have a richtext field...

#11178 report it
NkM at 2012/12/23 04:30am
Alternative method

I was trying to figure out if there was an actual Yii-specific way of doing an AJAX submit, but there doesn't seem to be any via the CActiveForm.clientOptions property. The closest AJAX'y thing I could find deals only with validation (and not submission). Though, I did find this tidbit in CActiveForm.clientOptions

afterValidate If the return value of this function is NOT true, the normal form submission will be cancelled.

In your CActiveForm options, set the clientOptions array to the following:

        'validateOnSubmit'=>true, // Required to perform AJAX validation on form submit
        'afterValidate'=>'js:mySubmitFormFunction', // Your JS function to submit form

Go ahead and setup your Javascript function

function mySubmitFormFunction(form, data, hasError){
    if (!hasError){
        // No errors! Do your post and stuff
        // FYI, this will NOT set $_POST['ajax']... 
        $.post(form.attr('action'), form.serialize(), function(res){
            // Do stuff with your response data!
            if (res.result)
    // Always return false so that Yii will never do a traditional form submit
    return false;

You really don't need to do anything special on the controller side with the exception that if you know you are going to processing an AJAX request (ala Yii::app()->request->isAjaxRequest and no $_POST['ajax']), you should be returning back a JSON object.

For example

// Validate ok! Saving your data from form okay!
// Send a response back!
header('Content-type: application/json');
echo json_encode('result'=>true, 'data'=>$modelDataOrSomeJunkToGiveBackToBrowser); // Use CJSON::encode() instead of json_encode() if you are encoding a Yii model
Yii::app()->end(); // Properly end the app

Edit: I should clarify, it is true that your actual Javascript function to submit the form won't create a $_POST['ajax'] by default, but Yii doing the AJAX validation will (which already happened in the last AJAX request prior to calling your Javascript submit form function). So you can use the same logic in your controller for the AJAX validation as if you set CActiveForm.enableAjaxValidation property to true.

#10591 report it
bonnie at 2012/11/06 07:51am

Will give it a try.

#10583 report it
sirin k at 2012/11/06 02:42am
Hi bonnie

hey bonnie.if you need to achive that usign this ajax form means you can simply use the below js code in your ajax response or success section.

              window.location="<?php echo Yii::app()->createAbsoluteUrl("controller/action");?>";
#10578 report it
bonnie at 2012/11/05 07:58pm
sirin k

Hi, is bonnie again I need to use this in my yii app. Can you show example of submitting data to the login controller then redirect the user to profile or any page. Thanks.

#9812 report it
sirin k at 2012/09/12 08:40am
Thanks bonnie

Thanks bonnie

#9811 report it
bonnie at 2012/09/12 08:19am
Nice one

I have been struggling with this you just saved my time.

Leave a comment

Please to leave your comment.

Write new article