I am working on my own forum system and I need to show popup messages after user actions, whether it’s a success message or a failure message.
I’ve made a big research and tried many methods to get this type of a system but the method that made the most sense in my case was using sessions as the trigger and also to store the message itself.
This is what I came up with:
function popupMessage(){ setTimeout(function(){ setTimeout(function(){ $('.popup_message').remove(''); }, 3000); $('.popup_message').fadeOut(); }, 3000); $('.header').append('<div class="popup_message success"><span><i class="fa fa-fw fa-check-circle"></i></span><p>success</p></div>'); }
This function is on my js file which holds all of my functions.
if(isset($_SESSION['message'])){ $message = $_SESSION['message']; echo ' <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script type="text/javascript" src="/assets/myscripts.js"></script> <script type="text/javascript"> var message = ''.$message.''; popupMessage() </script>'; unset($_SESSION['message']); }
That piece of code is on file which is included on the header of every page on my forum.
$_SESSION['message'] = 'success!'; header("Location: $location");
And those 2 rows are beeing executed for an example when a form is submitted.
The function popupMessage()
is working well by itself but it simply won’t work when I call it through the if(isset($_SESSION['message']))
condition.
When I’ve tried to replace the function call in a simple alert()
it was working fine which means that the message is set, but the function just wouldn’t run when it’s called through the condition.
Advertisement
Answer
You need to make sure you’re calling popupMessage()
below where the HTML of the popup message is created in the DOM due to the order of operations. Otherwise, you can load it in the $(document).ready();
function like so
$(document).ready(function() { popupMessage(); });
to ensure the HTML element exists before executing JS on it.