我有一个ajax表单,它被提交两次,因此在db中复制了两次相同的记录。
仅在启用客户端验证时才会发生此特定情况。
我也尝试过使用e.stopImmediatePropagation(),但这也会禁用显示错误消息,这在我的情况下不是解决方案。我希望验证和表单提交都能正常工作而不需要复制。
这是我的代码:
控制器:
public function actionIndex() {
$model = new Transaction();
if (isset($_POST['ajax']) && $_POST['ajax'] === 'transaction-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
if (Yii::app()->request->isAjaxRequest) {
$model->attributes = $_POST['Transaction'];
if($model->save()){
echo 'Success';
}
Yii::app()->end();
}
$this->render('index', array('model' => $model));
}
查看文件:
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'transaction-form',
'action' => Yii::app()->createUrl('transaction/index'),
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'BilledAmount'); ?>
<?php echo $form->textField($model,'BilledAmount',array('size'=>10,'maxlength'=>10)); ?>
<?php echo $form->error($model,'BilledAmount'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'ChargedAmount'); ?>
<?php echo $form->textField($model,'ChargedAmount',array('size'=>10,'maxlength'=>10)); ?>
<?php echo $form->error($model,'ChargedAmount'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'CardExpiry'); ?>
<?php echo $form->textField($model,'CardExpiry',array('size'=>4,'maxlength'=>4)); ?>
<?php echo $form->error($model,'CardExpiry'); ?>
</div>
<div class="row buttons">
<input name="submit" type="submit" value="Submit">
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<script>
$(function () {
$('form#transaction-form').on('submit', function (e) {
e.preventDefault();
var action = $("#transaction-form").attr('action');
var datas = $("#transaction-form").serialize();
$.ajax({
type: 'post',
url: action,
data: datas,
success: function (msg) {
if(msg == 'Success'){
location.reload();
}
}
});
return false;
});
答案 0 :(得分:0)
您的行动应如下所示:
public function actionIndex() {
$model = new Transaction();
if (Yii::app()->getRequest()->getIsAjaxRequest()) {
echo CActiveForm::validate($model);
Yii::app()->end();
}
if (isset($_POST['Transaction'])) {
$model->attributes = $_POST['Transaction'];
if($model->save()){
Yii::app()->user->setFlash('success', 'Transaction saved.');
$this->refresh();
}else{
Yii::app()->user->setFlash('error', 'Transaction saving error.');
}
}
$this->render('index', array('model' => $model));
}