How do you show flash messages after PJAX

I’m having trouble accessing session data that was processed via PJAX / AJAX.

In one instance of this I have flash messages being set in my model that get triggered via a PJAX / AJAX action. However, the flash messages don’t show until a full page refresh. How can I show a flash message was set via a PJAX / AJAX action without refreshing the page?

Here is an example of a flash message function

in main layout i have something like




<?php

foreach (Yii::$app->session->getAllFlashes() as $key => $message) {

echo '<div class="alert alert-' . $key . '">' . $message . '</div>';

}

?>



in my model I have something similar to




	public function beforeDelete() {

   	//do checks and set flash messages

	}

I suspect it being some dom element that isn’t reloading after the PJAX/AJAX call but not for certain at this point.

anyone?

In your action you need to echo (or return) alert then in javascript method (where you do the request) show response with alert.

Something like this.

Layout:




<div id="system-messages"></div>



Controller:




public function actionDelete($id)

{

   //delete your record

   

   echo '<div class="alert alert-success">Record has been successfully deleted</div>';

}



In javascript method where you do the request:




$.post(url, function(data) {

    // your code

    ('#system-messages').html(data)

});



I can explain how I work with alert messages.

Display alert messages with Alert widget which you can find in advanced template alert widget

Layout:




<?php

   if(Yii::$app->getSession()->getAllFlashes()) {

      $this->registerJs("$('#system-messages').fadeIn().animate({opacity: 1.0}, 4000). fadeOut('slow');");

   }

?>


<div id="system-messages" style="opacity: 1; display: none">

   <?= Alert::widget(); ?>

</div>



Controller:




public function actionDelete($id)

{

   //delete your record


   Yii::$app->session->setFlash('success', 'Record has been successfully deleted!');

}


// I have base AppController (parent controller) or you have put this method in each controller where you want to display messages.

public function afterAction($action, $result) 

{

   if (Yii::$app->request->isAjax && !empty(Yii::$app->session->getAllFlashes())) {

       echo Alert::widget();

   }

   return parent::afterAction($action, $result);

}



Javascript:

In javascript method when you do the request:




$.post(url, function(data) {

    // your code

    $('#system-messages').html(data).stop().fadeIn().animate({opacity: 1.0}, 4000).fadeOut('slow');

});



Css code:




#system-messages {

    right: 20px;

    position: fixed;

    top: 60px;

    width: 550px;

    z-index: 10;

}



So you don’t need write additional messages for ajax request just use Yii::$app->session->setFlash()

Thanks ron got this working.