Yii Framework Ajax Form Submit

- September 29, 2013
0 (0 votes)
Rate :
An easy way to send a form without reloading the page using Yii Framework

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>

Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter

– Eric S. Raymond

Have a better explanation?

If you have comments about this post. Please write your comments below

No comments associated with this article