Showing Confirmation/Error Messages in Web Apps
Just wanted to submit a quick tip about passing confirmation messages, etc.
I've been working on a complicated app that has many different messages displayed to users (for confirmation, errors, for validation, etc).
I'm sure there's better ways to do this, but I came up with a quick function to help me out.
Note: you must be using SESSIONS to use this function.
Check it out....
PHP Code:
function showMessage($msg = "")
{
if ($msg == "" && isset($_SESSION['showMessage']))
{
echo $_SESSION['showMessage'];
unset($_SESSION['showMessage']);
}
if ($msg != "")
{
$_SESSION['showMessage'] = $msg;
}
}
This function takes one argument: $msg.
If passed with a string, like 'showMessage("Foo")', it sets the string in a session variable, that can be displayed later. And since it's stored in SESSION, that means anywhere (on any page) later.
If, like me, you have a standard location on your page for displaying the messages, you just call the function without any arguments, like 'showMessage();', and it will display whatever message was previously set, and then unset the session variable, so that it doesn't get displayed again on accident.
I know it's very, very basic - but I just wanted to present the idea.
There are ways to change this to make it much more compatible with the Model/View/Controller idea as well - such as 'returning' the string, rather than simply echoing it, adding options to generate/echo CSS/HTML wrappers, etc.
Like I said, a simple idea. It happened to be all I needed at the time.
If you have a better way to do this, definitely share it. If anyone's interested, I'm sure they'd just love you for it. = )
Thanks,
Tommy George