Yii Framework Ajax Form Submit

alfa6661
- 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.

Controller

public function actionIndex()
{
    $model=new Message;
    if(isset($_POST['Message']))
    {
        $model->attributes=$_POST['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
                ));
            }
        }
        Yii::app()->end();
    }
    $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.

Views

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'message-form',
    'enableClientValidation' => true,
    'clientOptions' => array(
        'validateOnSubmit' => true,
        'validateOnChange' => false,
    ),
    'enableAjaxValidation'=>true,
)); ?>
 
<?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>
 
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton('Save', CHtml::normalizeUrl(array('ajax/index')),
    array(
        'dataType'=>'json',
        'type'=>'post',
        'success'=>'function(data) {
            if(data.status=="success"){
                $("#formResult").slideDown().html(data.message);
                $("#message-form")[0].reset();
            }
            else {
                $.each(jQuery.parseJSON(data.message), function(key, val) {
                    $("#message-form #" + key + "_em_").text(val);                                                    
                    $("#message-form #" + key + "_em_").show();
                });
            }
            $("#loading-container").hide();
        }',                    
        'beforeSend'=>'function(){                        
            $("#loading-container").show();
        }'
)); ?>
<span id="loading-container" style="display: none">
    <?php echo CHtml::image(Yii::app()->baseUrl . '/images/loading.gif'); ?>
</span>
</div>
 
<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