I have a form that looks like this
<?php
\yii\widgets\Pjax::begin(['id' => 'calculator-pjax']);
$form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => false,
'enableClientValidation'=> false,
'validateOnBlur' => false,
'validateOnChange' => false,
'validateOnSubmit' => false,
'options' => ['autocomplete' => 'off', 'data-pjax' => true],
]);
?>
...
...
<?= $form->field($model,'tax',
['template' => '
{label}
<div class="input-group mb-3">
{input}
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
{error}
</div>
{hint}
'])->textInput(['class' => 'form-control form-control-lg']); ?>
<?= Html::submitButton(Module::t('app', 'Calculate'), array('buttonType'=>'submit', 'class' => 'btn btn-lg')); ?>
<?php ActiveForm::end(); \yii\widgets\Pjax::end(); ?>
<div id="tax"> <!-- Jquery update here --> </div>
<div id="tax2"> <!-- Jquery update here --> </div>
<div id="tax3"> <!-- Jquery update here --> </div>
my javascript ajax post looks like this
$(document).ready(function () {
var $form = $("#<?= $model->formName() ?>");
$form.on("submit", function (event, messages) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({
"type":"POST",
"url":$form.attr('action'),
"data":$form.serialize(),
"dataType":"json",
"cache": true,
"success":function(data){
$("#tax").html(data.tax);
$("#tax2").html(data.tax2);
$("#tax3").html(data.tax3);
}
});
return false;
});
});
below is calculator action that returns a json
class calculatorAction extends Action
{
public function run()
{
$model = new calculator;
$model->scenario = calculator::SCENARIO_TAX;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
if ($model->validate())
{
$this->calculatetax();
die;
}
else
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
} else {
return $this->controller->render('calculator', [
'model' => $model,
]);
}
}
}
When I submit an empty form, I noticed in my console the ajax post it show the error, but it doesn’t reflect on the <form>
, instead it replaces the whole form the the error json
{ "calculator-tax": [ "Tax cannot be blank." ] }
Any idea what causes this or how to stop it from doing so? and how to update the <div>
with the update calculation results. thanks.