Answer the question
In order to leave comments, you need to log in
How to pass ajax on selected value to DropDownList and get response?
I have a product in it, I can select a category in the DropDownList and each category has specifications that should return to this product without reloading the page. There is an idea to do this through Ajax, but I don’t understand much how to write the script correctly. Don't be too hard on me, I'm new to this.
<?= $form->field($model, 'category_id')->dropDownList(ArrayHelper::map(
$categories,
'id',
title'
), ['prompt' => '']) ?>
<?php if (isset($model->category)) : ?>
<?= $form->field($model, 'options')->widget(MultipleInput::className(), [
'max' => isset($model->category->option) ? count($model->category->option) : null,
'enableGuessTitle' => false,
'allowEmptyList' => true,
'addButtonPosition' => MultipleInput::POS_HEADER, // show add button in the header
'columns' => [
[
'name' => 'options',
'items' => isset($model->category->option) ? $model->category->option : null,
'type' => 'dropDownList',
'title' => 'Опция',
'options' => [
'class' => 'js-select'
]
],
[
'name' => 'value',
'title' => 'Значение',
'items' => $model->value,
],
[
'name' => 'scale',
'items' => isset($model->category->scale) ? $model->category->scale : 'Выберете категорию',
'title' => 'Измерение',
'type' => 'dropDownList',
],
],
])->label(false);
?>
<?php endif; ?>
Answer the question
In order to leave comments, you need to log in
Good morning.
When changing the dropdown ajax can be sent like this:
<?= $form->field($model, 'country_id')->dropDownList(ArrayHelper::map(Countries::getAllName(), 'id', 'name_ru'),
[
'prompt' => 'Выбрать страну...',
'onchange' => '
$.post(
"'.Url::toRoute('ajax/list').'",
{id : $(this).val()},
function(data){
$("select#regions").html(data).attr("disabled", false)
}
)
'
]);
//это взаимосвязанный выпадающий список, куда будет подставлен результат работы ajajx
<?= $form->field($model, 'region_id')->dropDownList(ArrayHelper::map(Regions::getAllName(), 'id', 'name_ru'),
[
'prompt' => 'Выбрать регион...',
'id' => 'regions',
'disabled' => $model->isNewRecord ? 'disabled' : false
])
public function actionList()
{
if(Yii::$app->request->isAjax)
{
$id = (int)Yii::$app->request->post('id');
$regions = Regions::find()
->where('status=:status',[':status' => Regions::STATUS_ACTIVE])
->andWhere('country_id=:id', [':id' => $id])
->orderBy('name_ru')
->all();
foreach($regions as $region){
$this->option .= '<option value="'.$region->id.'">'.$region->name_ru.'</option>';
}
}
return $this->option;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question