Answer the question
In order to leave comments, you need to log in
Ajax form not validating after creating?
I'm adding a form using Ajax but it's not validating on the client. There is a form there, but based on the user's choice, part of the form changes. As follows, an ajax request is sent, it indicates what choice the user made, the form changes, and the same script, if a response is received, part of the form changes, in fact, this is how it is written in js
$('#deliveryForm .radio-tab input').change(function () {
var datas = $(this).val();
$.ajax({
method: "POST",
url: "/cart",
data: 'delivery='+datas,
success: function (data) {
$.pjax.reload({container: "#pjax-form-cart"});
$('#deliveryForm .radio-tabs .tab-pane').removeClass('active');
$('#deliveryForm .radio-tabs .tab-pane.delivery2').addClass('active');
}
})
});
public function actionIndex(){
if(Yii::$app->request->isAjax &&isset($post['delivery']))
$this->userCartChoice($post['delivery']);
$choice= UserCartChoice::find()->one();
...
}
private function userCartChoice($choise){
$userChoise=UserCartChoice::find()->one();
if(!$userChoise)
$userChoise= new UserCartChoice();
$userChoise->choice=$choise;
$userChoise->save();
}
<?php Pjax::begin(['id' => 'pjax-form-cart']); ?>
<div class="tab-content">
<div class="tab-pane delivery1 <?= ($userChoice==0)?'active':''?> ">
<?php if($userChoice==0){ echo PickUp::widget(['form'=>$form]); } ?>
</div>
<div class="tab-pane delivery2 <?= ($userChoice==1)?'active':''?>">
<?php if($userChoice==1){ echo DeliveryPiter::widget(['form'=>$form]); } ?>
</div>
</div>
<?php Pjax::end(); ?>
Answer the question
In order to leave comments, you need to log in
In general, I solved the issue as follows
<?php $this->registerJs("
$('#pjax-form-cart').on('pjax:end',function(){
$('#deliveryForm .required input').on('blur',function(){
var id= $(this).attr('id');
$('#deliveryForm').yiiActiveForm('validateAttribute', id);
})
});", yii\web\View::POS_READY); ?>
I understood you correctly that you decided instead of
<?php $form = ActiveForm::begin([
'action'=>'cart/checkout',
'method'=>'post',
'id'=>'deliveryForm',
'enableAjaxValidation' => true
]) ?>
Good afternoon.
This video will help you.
Pjax is not needed here at all.
You need to specify in the parameters that you need ajax validation, make an action for this validation and specify the address where the validation will take place.
Approximately like this:
$form = ActiveForm::begin([
'id' => 'testForm',
'enableAjaxValidation' => true,
//'enableClientValidation' => false,
'validationUrl' => ['dynamic/ajax-validation']
]);
// и действие в контролере
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question