1. PHP
  2. Yii Framework

Yii Framework Ajax Form Submit

This is a very simple snippets how to submit form using ajax. We create an example form with message field. By using CHtml::ajaxSubmitButton we can change the form to Ajax form. The form submits all the fields to the background server, the server processes and sends some data back to the front page. We receive the back data and show it out.


public function actionIndex()
    $model=new Message;
        if($model->save()) {
            echo CJSON::encode(array(
                'status' => 'success',
                'message' => $model->message
        else {
            $error = CActiveForm::validate($model);
            if($error!='[]') {
                echo CJSON::encode(array(
                    'status' => 'failed',
                    'message' => $error
    $this->render('index', array(
        'model' => $model

To return our data to an AJAX call, we have to echo and CJSON::encode. This is all we have to do with our PHP form processing.


<?php $form=$this->beginWidget('CActiveForm', array(
    'enableClientValidation' => true,
    'clientOptions' => array(
        'validateOnSubmit' => true,
        'validateOnChange' => false,
)); ?>

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

<div class="row">
    <?php echo $form->labelEx($model,'message'); ?>
    <?php echo $form->textArea($model,'message',array('cols'=>50)); ?>
    <?php echo $form->error($model,'message'); ?>

<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton('Save', CHtml::normalizeUrl(array('ajax/index')),
        'success'=>'function(data) {
            else {
                $.each(jQuery.parseJSON(data.message), function(key, val) {
                    $("#message-form #" + key + "_em_").text(val);                                                    
                    $("#message-form #" + key + "_em_").show();
)); ?>
<span id="loading-container" style="display: none">
    <?php echo CHtml::image(Yii::app()->baseUrl . '/images/loading.gif'); ?>

<div id="formResult" class="flash-notice" style="display:none"></div>
Comments to: Yii Framework Ajax Form Submit

    Your email address will not be published. Required fields are marked *

    Attach images - Only PNG, JPG, JPEG and GIF are supported.