A
A
Alexander Stepanov2018-01-31 03:04:56
Yii
Alexander Stepanov, 2018-01-31 03:04:56

How to pass Yii requests to javascript?

I found an article about ListView without paging and loading content on button click.
Link: www.elisdn.ru/blog/28/beskonechnaia-lenta-zapisei-s-ajax-dozagruzkoi-na-yii
The article is good and understandable, but for the first version of the framework.
I started to redo it and it seemed to work until I got to javascript.
My slightly redone script code looks like this:

// запоминаем текущую страницу и их максимальное количество
    var page = parseInt('<?php echo Yii::$app->request->get("page", 1); ?>');
    console.log(page);
    var pageCount = parseInt('<?php echo (int)$dataProvider->pagination->pageCount; ?>');

    var loadingFlag = false;

    $('#showMore').click(function()
    {
        // защита от повторных нажатий
        if (!loadingFlag)
        {
            // выставляем блокировку
            loadingFlag = true;

            // отображаем анимацию загрузки
            $('#loading').show();

            $.ajax({
                type: 'get',
                url: window.location.href,
                data: {
                    // передаём номер нужной страницы методом POST
                    'page': page + 1,
                    '<?php echo Yii::$app->request->csrfTokenFromHeader ?>': '<?php echo Yii::$app->request->csrfToken ?>'
                },
                success: function(data)
                {
                    // увеличиваем номер текущей страницы и снимаем блокировку
                    page++;
                    loadingFlag = false;

                    // прячем анимацию загрузки
                    $('#loading').hide();

                    // вставляем полученные записи после имеющихся в наш блок
                    $('#listView').append(data);

                    // если достигли максимальной страницы, то прячем кнопку
                    if (page >= pageCount)
                        $('#showMore').hide();
                }
            });
        }
        return false;
    });

But none of the php echo returns what you want when called in javascript, but are displayed fine in php.
In javaScript, I'm even worse than in php, but I brought the script to the point that it began to respond to a click, but I can't get the data.
Please tell me how to win this and how to get these echo correctly?
Just for anyone, I bring the rest of the code of this solution, which I got:
Model:
public function getNewDataProvider()
    {
        $query = Product::find()->where(['new' => 1]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 2,
            ],
        ]);
        return $dataProvider;
    }

Controller:
public function actionNew()
    {
        $dataProvider = Product::getNewDataProvider();

        if (\Yii::$app->request->isPjax){
            return $this->renderPartial('_loop', [
                'dataProvider' => $dataProvider,
            ]);
        } else {
            return $this->render('new', [
                'dataProvider' => $dataProvider
            ]);
        }
    }

Index view:
<?php Pjax::begin([
    'id' => 'productList',
    'enablePushState' => false,
//    'enableReplaceState' => false,
]); ?>

<?= $this->render('_loop', ['dataProvider' => $dataProvider]); ?>

<?php Pjax::end(); ?>

Helper _loop:
<?= ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '_view',
    'layout' => "{items}\n{summary}",
]); ?>

<?php if ($dataProvider->totalCount > $dataProvider->pagination->pageSize): ?>


    <p id="loading" style="display:none"><img src="<?php echo Yii::$app->request->baseUrl; ?>/images/loading.gif" alt="" /></p>
    <p id="showMore">Показать ещё</p>

<?php endif; ?>

_view helper:
<h2><?= Html::encode($model->title) ?></h2>
    <?= HtmlPurifier::process($model->description) ?>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question