Last active
August 17, 2018 08:07
-
-
Save fedorovanton/a9c59e686d7477b47393fef218761137 to your computer and use it in GitHub Desktop.
Отправка данных ActiveForm с помощью Ajax (с пост-оберткой)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Контроллер ClientController: | |
============================ | |
public function actionAdd() | |
{ | |
$model = new AddClientOwnerForm(); | |
if(Yii::$app->request->isAjax){ | |
if($model->load(Yii::$app->request->post())) { | |
// ... ваш обработчик данных... | |
if ($model->save()) { | |
return '<option value="'.$model->id.'">'.$model->fio.' ('.$model->phone.','.$model->email.')</option>'; | |
} else { | |
return '<script>alert("Ошибка добавления в БД")</script>'; | |
} | |
} | |
} | |
} | |
Вьюха form.php: | |
============================ | |
<?php $form = ActiveForm::begin(['action' => ['client/add'], 'method' => 'post', 'id' => 'form-client-add']); ?> | |
<div class="modal-body"> | |
<?= $form->field($clientModel, 'fio')->textInput(['maxlength' => true, 'placeholder' => 'Иванов Иван']) ?> | |
<?= $form->field($clientModel, 'phone')->textInput(['maxlength' => true, 'placeholder' => '89101234567']) ?> | |
<?= $form->field($clientModel, 'email')->textInput(['maxlength' => true, 'placeholder' => 'почта_собственника@mail.ru']) ?> | |
<?= $form->field($clientModel, 'category')->dropDownList(Client::getCategoryOwnerArray()) ?> | |
<?= $form->field($clientModel, 'city_id')->dropDownList(City::getCityList()) ?> | |
</div> | |
<div class="modal-footer"> | |
<?= Html::submitButton('<i class="fa fa-save"></i> Добавить', ['class' => 'btn btn-warning', 'id' => 'btn-client-add']) ?> | |
</div> | |
<?php ActiveForm::end(); ?> | |
<?php | |
$js = <<<JS | |
$('#form-client-add').on('beforeSubmit', function(){ | |
var data = $(this).serialize(); | |
$.ajax({ | |
url: '/client/add', | |
type: 'POST', | |
data: data, | |
success: function(res){ | |
$('#addclientownerform-fio').val(''); | |
$('#addclientownerform-phone').val(''); | |
$('#addclientownerform-email').val(''); | |
$('#addClientModal').modal('hide'); | |
$('#object-client_id').append(res); | |
$("#object-client_id :last").attr("selected", "selected"); | |
}, | |
error: function(){ | |
alert('Error!'); | |
} | |
}); | |
return false; | |
}); | |
JS; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment