yii验证ajax表格帖子

时间:2014-05-02 10:49:52

标签: jquery ajax yii

我正在尝试使用Yii制作一个ajax计算器。我知道我可以使用javascript,但由于我是Yii的新手,我想了解事情是如何运作的。

这是我视图中的代码

$form = $this->beginWidget('CActiveForm', array(
        'id'=>'loan-calculator-form', 
        'enableAjaxValidation'=>false, // thisturns off AJAX validation 
        'enableClientValidation'=>true,
        'clientOptions'=>array( 
                'validateOnSubmit'=>true,
                'validateOnChange'=>true, 
        ), 
)); ?>


<div class="row">
    <?php echo $form->errorSummary($model); ?>
    <div class="col-md-6">
        <div class="form-body">
            <div class="form-group">
                <?php echo $form->labelEx($model,'price'); ?>
                <div class="input-group input-group-lg">
                    <span class="input-group-addon">RM</span>
                    <?php echo $form->textField($model,'price',array('class' => 'form-control')); ?>
                </div>
                <?php echo $form->error($model,'price'); ?>
            </div>
            <div class="form-group">
                <?php echo $form->labelEx($model,'downpayment'); ?>
                <div class="input-group input-group-lg">
                    <span class="input-group-addon">RM</span>
                    <?php echo $form->textField($model,'downpayment',array('class' => 'form-control')); ?>
                </div>
                <?php echo $form->error($model,'downpayment'); ?>
            </div>
            <div class="form-group">
                <?php echo $form->labelEx($model,'rate'); ?>
                <div class="input-group input-group-lg">
                    <?php echo $form->textField($model,'rate',array('class' => 'form-control')); ?>

                    <span class="input-group-addon">%</span>
                </div>
                <?php echo $form->error($model,'rate'); ?>
            </div>

        </div>
        <?php echo $form->error($model,'yearloan'); ?>
    </div>
</div>
<div class="form-footer">


    <?php echo CHtml::submitButton("Calculate", 
            array('buttonType'=>'submit', 'class' => 'btn btn-lg btn-warning btn-block',
                                                                 'onclick'=>"calcLoan();"
                                                                 )
    );
    ?>

    <script type="text/javascript">
        function calcLoan()
        {
            <?php echo CHtml::ajax(array(
                'url'=>array('/loan-calculator'),
                'data'=> "js:$(this).serialize()",
                'type'=>'post',
                'dataType'=>'json',
                'cache' => true, 
                'success'=>"function(data)
                    {
                        $('#totalLoanAmount').html(data.totalLoanAmount);
                        $('#monthlyInstallment').html(data.monthlyInstallment);
                        $('#loanCalcTable').html(data.loanCalcTable);
                    } ",
            ));
            ?>
            return false; 

        }
    </script>

在我的模型中,我确实添加了“必需”

等适当的规则

但是当我按下表单上的提交时,错误客户端错误检查工作。如果表单有效,表单将发布,onlick也将执行。我不希望表格发布。我想使用ajax帖子。

当我设置enableAjaxValidation'=>true, 'enableClientValidation'=>true, without the 'clientOptions' array并提交表单时。当有错误时,ajax帖子仍然会发生。它返回这个json

{"CalculatorsForm_price":["Car Purchase Price cannot be blank."],"CalculatorsForm_downpayment":["Down Payment cannot be blank."],"CalculatorsForm_rate":["Interest Rate cannot be blank."]}

如果表格有效,我会在那里做一个ajax帖子吗?

2 个答案:

答案 0 :(得分:0)

而不是CHtml::submitButton()使用以下代码 -

<?php
echo CHtml::ajaxSubmitButton(
    'Continue',
    CHtml::normalizeUrl(array('/loan-calculator')),
    array(
        'type'=>'post',
        'dataType'=>'json',
        'success'=>'js:function(data){
             if(data.status == "success") {
                  [.....]
             } else {
                  $.each(data, function(key, val) {
                       if(document.getElementById(key+"_em_"))
                            document.getElementById(key+"_em_").innerHTML = val;
                       $("#loan-calculator-form #"+key+"_em_").show();
                  });
             }
        }'
    ),
    array(
         'name'=>'submit',
         'class'=>'btn btn-lg btn-warning btn-block'
    )
);
?>

请相应地进行更改。

我希望它有所帮助。

答案 1 :(得分:0)

使用afterValidate属性

    <?php 
    $form=$this->beginWidget('CActiveForm', array
    (
        'id'=>'loan-calculator-form',
        'enableAjaxValidation' => true,
        'enableClientValidation'=>true,
        'clientOptions'=>array
        (
            'validateOnSubmit'=>true,
            'afterValidate'=>'js:function(form,data,hasError)
            {
                if(!hasError)
                {
                    $.ajax
                    ({
                            "type":"POST",
                            "url":"'.CHtml::normalizeUrl(array("controller/action")).'",
                            "data":form.serialize(),
                            "success":function(data){},                                        
                     });
                 }
              }'
        ),
    )); 
    ?>

    ........
    Your form fields
    ......

    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

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