The simple solution is to create a model form, controller and view to display your alert and then use AJAX to display the message.
First, we will add a DIV
container with an id of jquery-alert-message-container
to our main layout (line 6
) views/layouts/main.php
. This is so that all pages that use this main layout can use this area to display our alert message.
In the site controller we will add a new action called alert
. If you are using yii\filters\AccessControl
, set permission so everyone has access to this action.
This is the model form we are using for the alert. For the purpose of this demo is called frontend\models\JqueryAlertForm.php
Finally, we render the alert using this view frontend/views/site/_alert
:
Now lets create a view to use our new alert. To do this we just need one line of JavaScript. Line 45
, calls our site/alert
action and passes the message and message type as a POST
and then loads the result into the jquery-alert-message-container
DIV
.
This is the site controller used to render the above view: