I would like to display a popup message on a HTML page only if I had clicked on a button and had sent successfully a form from another one. I tried to do that with PHP sessions (including JavaScript of course), and I see everything is OK, but the page where’s the popup on, display the popup also when I directly go to it, not from the form submission’s page. I would like to display it only, when I go from the form’s page with successful form sending.
Here’s the form submission page code (form.php):
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//database
if ($stmt->execute()) {
$_SESSION['successMessage'] = "Correctly saved";
$_SESSION['fromForm'] = true;
header('Location: secondpage.php');
exit;
}
}
?>
<form method="POST">
<input type="text" name="field1" required>
<button type="submit">Submit</button>
</form>
Here’s the popup message’s page code (second.php)
<?php
session_start();
?>
<body>
<div id="popupMessage" class="popup-message">
<span class="popup-icon">!</span>
<span class="popup-text" id="popupText"></span>
</div>
<?php
if (isset($_SESSION['fromFORM']) && $_SESSION['fromFORM'] === true) {
if (isset($_SESSION['successMessage'])) {
echo '<script type="text/javascript">',
'showPopupMessage("' . $_SESSION['successMessage'] . '");',
'</script>';
unset($_SESSION['successMessage']);
}
unset($_SESSION['fromFORM']);
}
?>
<script src="script.js"></script>
And the JavaScript file (script.js):
function showPopupMessage(message) {
const popup = document.getElementById('popupMessage');
const popupText = document.getElementById('popupText');
popupText.textContent = message;
popup.classList.add('show');
setTimeout(() => {
popup.classList.remove('show');
}, 3000); // The message will disappear after 3 seconds
}
Benedek Szabó is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
You have to load script.js
before you try to call the functions it defines. So move <script src="script.js"></script>
up in your script.
And use json_encode()
to encode the value of the message in case it contains special characters that need to be escaped.
<?php
session_start();
?>
<body>
<div id="popupMessage" class="popup-message">
<span class="popup-icon">!</span>
<span class="popup-text" id="popupText"></span>
</div>
<script src="script.js"></script>
<?php
if (isset($_SESSION['fromFORM']) && $_SESSION['fromFORM'] === true) {
if (isset($_SESSION['successMessage'])) {
echo '<script type="text/javascript">',
'showPopupMessage(' . json_encode($_SESSION['successMessage']) . ');',
'</script>';
unset($_SESSION['successMessage']);
}
unset($_SESSION['fromFORM']);
}
?>