Search code examples
yii2pjax

using pjax for toasts without full refresh


  • Pjax for Alerts

There is alert.php included in layout file above $content. This is as below :

<?php Pjax::begin(['id'=> 'new-alert','enablePushState' => false]); ?>
        <?= \odaialali\yii2toastr\ToastrFlash::widget([
                'options' => [
                    'positionClass' => 'toast-bottom-full-width',
                    //'progressBar' => true,
                    'timeOut' => 6000,
                    'extendedTimeOut' => 2000                       
                ]
         ]);?>
<?php Pjax::end(); ?>

And to get flash messages in ajax , there are calls to below container

$.pjax.reload({container:'#new-alert'});

This results in showing of alert messages but also sends an Ajax request to URL whichever page is open. Can we trigger request to "/site/toast" on ajax calls which can renderAjax the above widget inplace of making ajax request on current url ?

Since there are no html "a" tag well as neither any "form" tag here inside widget generated html, Is this correct use of pjax ?

http://localhost:8081/about-us?_pjax=%23new-alert
  • Pjax for form

    Also if we wrap an Active Form inside Pjax, how can we make sure that none of A tags or nested Form trigger a Pjax request except the container form ?


Solution

  • I have removed call for pjax from PHP and made alert as below -

    <div id="new-alert">
    
            <?= \odaialali\yii2toastr\ToastrFlash::widget([
                        'options' => [
                            'positionClass' => 'toast-bottom-full-width',
                            //'progressBar' => true,
                            'timeOut' => 6000,
                            'extendedTimeOut' => 2000                       
                        ]
            ]); ?>
    
    </div>
    

    Instead I am making pjax call from javascript as below -

    $.pjax({url: encodeURI(baseUri + "site/toast"), container: '#new-alert', push: false})
    
    public function actionToast() 
    {               
        if(Yii::$app->request->getHeaders()->has('X-PJAX'))
        {
            return $this->renderAjax('//common/alert');
        }
        else
        {
            return $this->redirect(Yii::$app->request->referrer);           
        }
    }
    

    $.pjax.reload was previously retrieving additional toasts if there were some for current url as well. Above solution only gets toasts related to ajax.