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
By default How to enable gridview ajax in gii crud?
Whenever i create crud i need to add by default gridview with ajax.
Thanks
Title
By default pjax leaves nearly no time for the request to complete before doing a full page refresh, this stops it.
$.pjax.defaults.timeout = false;//IMPORTANT $.pjax.reload({container:'#container_id'});
POST method with Pjax
Maybe it would be helpful for people like me who want the gridView to be posted via POST instead of deafult GET method.
And also such default grid urls after applying filter aren't pretty at all
http://site.dev/admin-crud/index?AdminCrudSearch[username]=&AdminCrudSearch[role]=3&AdminCrudSearch[status]=&AdminCrudSearch[created_at]=
Pjax::begin(['id' => 'admin-crud-id', 'timeout' => false, 'enablePushState' => false, 'clientOptions' => ['method' => 'POST']])
tutorial
to complete this post, a nice tuto with example here
how to make pjax works for Action button ?
by default, Pjax doesnt work with GridView action button. How do I make pjax works with them ?
how to update two pjax on single jquery action
i tried to reload two of pjax with single jquery action but only the first one executed. any help ?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.