How to use GridView with AJAX

With the adoption of PJax on Yii2 things  have change quite a bit with GridView when it comes to work with them in AJAX mode. It will probably be confusing at the beginning, but then you will soon realize how powerful the new approach is.

Using PJax widget

The way to work with GridView in AJAX mode, is by using the PJax widget. The basic usage is like the following:

<?php \yii\widgets\Pjax::begin(); ?>
<?= GridView::widget([
// ... configuration here
]);
<?php \yii\widgets\Pjax::end(); ?>

Thats it, from now, the links and forms (filtering) on your GridView widget will work on ajax mode. But wait a minute, how come the action buttons do not work on AJAX mode? Well, if you check closely the rendered HTML, you will see that the links do have the HTML5 attribute data-pjax="0". That means that if you don't wish PJax to handle your links, you need to add this HTML5 attribute to them.

How to Update my GridView

You will surely missing $('#grid').yiiGridView('update') and wondering how to do it with PJax. The following code comes to the rescue:

// on your javascript
// I highly recommend that you setup the id of your PJax widget
$.pjax.reload({container:'#idofyourpjaxwidget'});

For more information about the options that you can pass to the reload function, please check the PJax plugin code.

Final Notes

The PJax widget works with any links and/or forms that are inside its begin() and end() statements. That means, that this tutorial is also valid for ListView, LinkPager, etc... Anything that holds a link and/or a form.

HappYii2 coding