A
A
AlexSer2019-07-17 07:56:56
Yii
AlexSer, 2019-07-17 07:56:56

How to work with Pjax in yii2?

i have a quick search form

<?php yii\widgets\Pjax::begin(['id' => 'new_note']) ?>
        <?= Html::beginForm(['/system/system/fastsearch'], 'post', ['data-pjax' => '','enctype' => 'multipart/form-data', 'class'=>'form-inline' ]) ?>
        <?= Html::input('text', 'search', "", ['class' => "form-control form-control-sm ml-3 w-75"]) ?>
        <?= Html::submitButton('<i class="glyphicon glyphicon-search"></i>&nbsp;Найти', ['class' => 'btn btn-default', 'id'=>'press_search'])?>
        <?= Html::endForm() ?>
        <?php Pjax::end(); ?>

The view is rendered in actionIndex(); The search request is passed to actionFastsearch();
The question is how to display the received data in the desired div?
And why do I have routing to url in action?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-07-17
@AlexSer

Good morning.
Pjax only deals with content between begin() and end().
Therefore, you can simply add the desired div after the form.
Form code.

<?php
   yii\widgets\Pjax::begin(['id' => 'new_note', 'enablePushState' => false]) ?>
        <?= Html::beginForm(['/system/system/fastsearch'], 'post', ['data-pjax' => '1','enctype' => 'multipart/form-data', 'class'=>'form-inline' ]) ?>
        <?= Html::input('text', 'search', "", ['class' => "form-control form-control-sm ml-3 w-75"]) ?>
        <?= Html::submitButton('<i class="glyphicon glyphicon-search"></i>&nbsp;Найти', ['class' => 'btn btn-default', 'id'=>'press_search'])?>
        <?= Html::endForm() ?>
        <div id="reload-pjax"><?= $search ?? null ?></div>
    <?php Pjax::end();
?>

The action in the controller can be like this.
public function actionFastsearch()
{
    if(Yii::$app->request->isAjax){
        $search = Yii::$app->request->post('search');
        return $this->render('index', ['search' => $search]);
    }
}

Or, which in my opinion is better, submit the form and process the server response using plain js or jquery.
PS
Although you can use this option. The form field must be filled in mandatory.
<?php
Pjax::widget([
    'id' => 'reload-pjax',
    'enablePushState' => false, 
    'enableReplaceState' => false, 
    'formSelector' => '#options-form',
    'submitEvent' => 'submit',])
?>
<?= Html::beginForm(['/site/fastsearch'],
                    'post',
                    [
                        'class'=>'form-inline',
                        'id' => 'options-form'
                    ]) ?>
<?= Html::input('text', 'search', "", ['class' => "form-control form-control-sm ml-3 w-75"]) ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-search"></i>&nbsp;Найти', ['class' => 'btn btn-default', 'id'=>'press_search'])?>
<?= Html::endForm() ?>
<div id="reload-pjax"></div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question