Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Pjax not working

I want to refresh the gridview using Pjax but somehow it is not working. Here is the code:

_search.php

    <?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

$this->registerJs("
                  $('#btnAjaxSearch').click(function(){
                        $.ajax({
                                type: 'get',
                                data: $('.bank-search form').serializeArray(),
                                success: function (data) {
                                      $.pjax.reload({container:\"#bank\"});
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                      alert('error');
                                }
                        });
                       return false;
                  });
                ", \yii\web\View::POS_END, 'bank-search');
?>

<div class="bank-search">
    <?php Pjax::begin(['id' => 'bank-form']); ?>
    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'bank_name') ?>

    <?= $form->field($model, 'state') ?>

    <?= $form->field($model, 'district') ?>

    <?= $form->field($model, 'city') ?>

    <div class="form-group">
        <?= Html::Button('Search', ['class' => 'btn btn-primary','id' => 'btnAjaxSearch']) ?>
    </div>

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

</div>

index.php

    <?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax; 

$this->title = 'Banks';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="bank-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php  echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Bank', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?php Pjax::begin(['id' => 'bank']); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'bank_name',
            'state',
            'district',
            'city',
            // 'branch',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
    <?php Pjax::end(); ?>
</div>

Controller

 /**
     * Lists all Bank models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BankSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

Simple search is working but Pjax is not. I am new to Yii2 so any help would be appreciated. Thank you.

like image 231
Chinmay Waghmare Avatar asked Mar 07 '15 04:03

Chinmay Waghmare


2 Answers

Thanks Edin. It helped me to solved the problem. Here is what I did. It might help someone facing the same problem.

As Edin mentioned you need to pass the url along with the search parameters to the Pjax in order to refresh the gridview.

Here's my edited code :

    $js = <<<JS
        // get the form id and set the event
        $('#bank-form-id').on('beforeSubmit', function(e) { 
           var form = $(this);
            if(form.find('.has-error').length) {
                return false;
            }
            $.ajax({
                url: form.attr('action'),
                type: 'post',
                data: form.serialize(),
                success: function(response) { 
                    var csrf = yii.getCsrfToken();
                    var bank_name = $('#banksearch-bank_name').val();
                    var state = $('#banksearch-state').val();
                    var district = $('#banksearch-district').val();
                    var city = $('#banksearch-city').val();
                    var url = form.attr('action')+ '&_csrf='+csrf+'&BankSearch[bank_name]='+bank_name+'&BankSearch[state]='+state+'&BankSearch[district]='+district+'&BankSearch[city]='+city;
                    $.pjax.reload({url: url, container:'#bank'});
                }
            });    
        }).on('submit', function(e){
        e.preventDefault();
    });
JS;
$this->registerJs($js);
like image 141
Chinmay Waghmare Avatar answered Nov 07 '22 13:11

Chinmay Waghmare


The way Pjax is working is by sending another request with special headers. When pjax request is detected only html required to update container is returned from server. Line

$.pjax.reload({container:\"#bank\"});

will send another request, and inside actionIndex queryParams will be empty.

You can solve this by storing search parameters to session or by specifing pjax url with parameters in query string.

Try following:

  var url = urlWithFilters(); 
  $.pjax({url: url, container: '#bank'});

In this case you don't need to create own ajax call, just create url with with filters.

like image 38
Edin Omeragic Avatar answered Nov 07 '22 11:11

Edin Omeragic