Answer the question
In order to leave comments, you need to log in
How to fix an error in ajax request?
Hello.
There is an ActiveForm in which the radio is in the modal window, but the problem is that the values are not saved to the database, it shows alert('fail');
<?php $form = ActiveForm::begin([
'id' => 'formTest',
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
]);
$list = [0 => 'one', 1 => 'two', 2 => 'three'];
?>
<?= $form->field($model, 'name')->radioList($list)->label(false); ?>
<div class="form-group">
<?= \yii\helpers\Html::submitButton('<i class="glyphicon glyphicon-ok"></i> Ok', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
$js = <<< JS
$(document).ready(function() {
$('form#formTest').on('beforeSubmit', function () {
var data = $(this).serialize();
$.ajax({
type: 'post',
url: 'message',
data: data,
error: function() {
console.log('error');
},
success: function(){
console.log(data);
},
})
.done(function(data) {
if(data.success) {
alert('success');
} else {
alert('fail');
}
});
return false;
});
});
JS;
public function actionMessage()
{
$model = new Post();
if(\Yii::$app->request->isAjax) {
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->save();
}
}
return $this->renderAjax('message', [
'model'=>$model,
]);
}
Answer the question
In order to leave comments, you need to log in
This condition is probably never met in your code by if(data.success) since you don't return anything from the controller except the form. You need to return a positive response upon successful saving of the model
I redid it a little, now it works, but the button is essentially not needed, when switching radioboxes, the value is immediately saved to the database. How can I make it save after clicking submit? What to fix?
Now it works without js.
view
<?php $form = ActiveForm::begin([
'id' => 'formTest',
'method' => 'POST',
'enableAjaxValidation' => true,
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => [
'showErrors' => true,
'labelSpan' => 1,
'deviceSize' => ActiveForm::SIZE_SMALL,
]
]);
?>
<?= $form->field($model, 'Name')->radioList($list)->label(false); ?>
<?php ActiveForm::end(); ?>
public function actionMessage($id)
{
$model = Orders::findOne($id);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
if ($model->save()) {
return $this->renderAjax('message', [
'model'=>$model,
]);
} else {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
return $this->renderAjax('message', [
'model'=>$model,
]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question