How can I update view if I trigger Ajax from a JS ?
I want to update _partialCategory.php when user clicks on parent category.
Schenario:
- User click on a custom design parent category div.
- On click I want to load its child category by replacing the parent category.
I m able to populate parent category.
I m also able to make a ajax call to the controller but
I m not able to update view based on new data from ajax call.
getChildCategory.js
function getChildCategory(parentId){
var url = '/site/get-child-category';
var data = { id : parentId};
$.ajax({
url: url,
type: 'get',
dataType: 'json',
data: data
})
.done(function(response) {
if (response.data.success == true) {
alert(response.data.message);
}
})
.fail(function() {
console.log("error");
});
}
Sitecontroller.php
public function actionGetChildCategory($id){
$category = Category::find()
->where(['parent_id' => $id])
->orderBy('id')
->asArray()
->all();
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
if ($category != null) {
$message = 'Please select child category';
return [
'data' => [
'success' => true,
'data' => $category,
'message' => $message,
],
'code' => 0,
];
} else {
return [
'data' => [
'success' => false,
'data' => null,
'message' => 'An error occured.',
],
'code' => 1, // Some semantic codes that you know them for yourself
];
}}else{
return "Outside isAjax";
}
}
index.php
<?= $this->render('_partialCategory', array('category'=>$category)); ?>
_partialCategory.php
<?php
/* @var $category \backend\models\Category */
foreach ($category as $item) { ?>
<div class="cat-wrapper category">
<div class="card-block radio">
<div class="row justify-content-center d-flex">
<div class="cat-icon">
<i class="<?= $item['imagepath'] ?>"></i>
</div>
</div>
</div>
<h5 class="cat-name"><?= $item['name'] ?></h5>
<p class="cat-id" value="<?= $item['id'] ?>"></p>
</div>
<?php } ?>