Answer the question
In order to leave comments, you need to log in
How to send data from a form using ajax and process it in the controller?
On the index page, a GridView is rendered, the GridView renders models and actions to them (view, update, delete).
When you click on action update, a form opens with the ability to upload a file. I decided to do it differently. When you click on the action, a pop-up window is created (jquery confirm library), and the content (view update) is loaded in it. When you click on the save button in the view, everything works fine, but it looks ugly. Then I decided to remove the save button from the update view and add it to the popup. This is where things get interesting for me. The form data is sent and saved, but the image is not. I read something about form data in js. But something did not help or requires some special processing?
index
$('.action-update').click(function (e) {
var title = $(this).data('title')
var link = $(this).val()
$.alert({
title: title,
content: 'url:' + link,
columnClass: 'col-6',
containerFluid: true,
buttons: {
saveButton: {
text: 'Сохранить',
btnClass: 'btn-green',
action: function () {
$.ajax({
url: link,
method: 'post',
data: $('form').serialize(),
success: function () {
console.log(1)
}
})
}
},
closeButton: {
text: 'Закрыть'
}
}
})
});
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\Specialist */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="specialist-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'birthday')->textInput(['type' => 'date']) ?>
<?= $form->field($model, 'dental_profile')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'basic_education')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'additional_education')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'experience')->textInput(['type' => 'date']) ?>
<?= $form->field($model, 'about')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'image')->fileInput() ?>
<?= $form->field($model, 'active')->checkbox() ?>
<div class="form-group">
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
public function actionUpdate($id)
{
$this->layout = false;
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (UploadedFile::getInstance($model, 'image')) {
$model->uploadImage();
}
return !$model->hasErrors() ? $this->asJson(['status' => true]) : $this->asJson(['status' => false, 'message' => $model->getErrors()]);
}
return $this->render('update', [
'model' => $model,
]);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question