Answer the question
In order to leave comments, you need to log in
Pjax how to switch view for data?
Good evening.
There is an ad site.
It is necessary to organize the output of ads with two different views (list, tiles). The choice of representation should be carried out by clicking on the corresponding link.
Now there is a code
// ССЫЛКИ ДЛЯ ВЫБОРА ФОРМАТА ВЫВОДА.
<?= Html::a('List', ['car/view-mode'], ['data' => ['view-mode' => 1]]) ?>
<?= Html::a('Gallery', ['car/view-mode'], ['data' => ['view-mode' => 2]]) ?>
// ДЕЙСТВИЕ В КОНТРОЛЛЕРЕ УСТАНАВЛИВАЕТ COOKIE
// кроме этого действия в контроллере есть ещё одно действие actionSearchCar(), которое осуществляет поиск и вывод объявлений.
//но его использовать очень не удобно,
// много кода, куча условий, легко поломать, тяжело исправить.
<?php
public function actionViewMode($id)
{
if(Yii::$app->request->isAjax){
$viewModeCookie = Yii::$app->response->cookies;
$viewModeCookie->add(new \yii\web\Cookie([
'name' => 'view-mode',
'value' => $id
])
);
$render_file = ($id == 1) ? '_gallery' : '_list';
return $this->renderAjax('_includes/' . $render_file);
}
}
?>
// ВЫВОД ДАННЫХ НА СТРАНИЦЕ
<?php Pjax::begin([
'id' => 'view-mode-pjax',
'timeout' => 10000,
'enablePushState' => false,
'enableReplaceState' => false,
'linkSelector' => '.vmpjax'
]) ?>
<div id="view-mode-pjax">
<!-- ВЫБОР ПОДКЛЮЧАЕМЫХ ФАЙЛОВ ДЛЯ ВЫВОДА ОБЪЯВЛЕНИЙ СПИСКОМ ИЛИ ГАЛЕРЕЕЙ -->
<?php if($viewModeCookieValue == 2){ ?>
<?= $this->render('_includes/_list', ['cars_res' => $cars_res, 'pages' => $pages]) ?>
<?php }elseif ($viewModeCookieValue == 1){ ?>
<?= $this->render('_includes/_gallery', ['cars_res' => $cars_res, 'pages' => $pages]) ?>
<?php } ?>
</div>
<?php Pjax::end(); ?>
Answer the question
In order to leave comments, you need to log in
Worrying for nothing, problem solved.
When a link is clicked, an ajax action request is sent, where cookies are set, and then the desired block is reloaded in success using PJAX.
$('a.vmpjax').click(function (e) {
e.preventDefault();
$(this).addClass('active').closest('li').siblings().find('a').removeClass('active');
var viewMode = $(this).attr('data-view-mode');
var url = $(this).attr('href');
$.ajax({
type: "GET",
url: url,
data: {
'id': viewMode
},
success: function (data) {
$.pjax.reload({container: "#view-mode-pjax", url: window.location.href, timeout: 0 });
}
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question