Question

i have an issue with a session message that prints a blank pop up when i enter the page. There is no message in it. It is meant to create messages like page deleted or page created. It works except for the issue at the start when u enter the page, it will show a blank pop up message.

Session.php

<?php
ini_set('session.bug_compat_warn', 0);
ini_set('session.bug_compat_42', 0);
session_start();

function message() {
    if (isset($_SESSION["message"])) {

      $output = htmlentities($_SESSION["message"]);


      //clear message after use
      $_SESSION["message"] = null;
      return $output;   
      }
    }

    function errors() {
    if (isset($_SESSION["errors"])) {
      $errors = $_SESSION["errors"];

      //clear message after use
      $_SESSION["errors"] = null;
      return $errors;   
      }
    }

?>

Page

<?php require_once("includes/session.php"); ?>

<div id="page">
<?php  $alertmessage= message(); ?>

<?php echo "<script type='text/javascript'>alert('{$alertmessage}');</script>"; ?>

    <h2>Manage Admins</h2>

    <table>
        <tr>
            <th style="text-align: left; width: 200px;">Username</th>
            <th colspan="2" style="text-align: left;">Actions</th>
        </tr>

        <?php while($admin = mysqli_fetch_assoc($admin_set)) { ?>
        <tr>
            <td>
                <?php echo htmlentities($admin["username"]); ?>
                <br />
                <?php //echo htmlentities($admin["hashed_password"]); ?>
            </td>
            <td><a href="edit_admin.php?id=<?php echo urlencode($admin["id"]); ?>">Edit</a></td>
            <td><a href="delete_admin.php?id=<?php echo urlencode($admin["id"]); ?>" onClick="return confirm('Are you sure you want to delete this admin?')">Delete</a></td>
        </tr>
    <?php } ?>
    </table>

<br/>

    <table>
        <tr>
            <td><a href="new_admin.php">Add new admin</a></td>
        </tr>
    </table>
</div>
Was it helpful?

Solution

You should check if message is not empty in your page template. Easiest solution wold be to change message() and errors() to return false if there is no message in session:

function message() {
    if (isset($_SESSION["message"])) {

      $output = htmlentities($_SESSION["message"]);


      //clear message after use
      $_SESSION["message"] = null;
      return $output;   
      }
      return false;
    }

And then in you template you should check if $alertmessage is not false before you echo javascript:

<?php if($alertmessage) 
      echo "<script type='text/javascript'>alert('{$alertmessage}');</script>";?>

OTHER TIPS

If you return false from your functions if there are no messages then you can just go

<?php 
if ($alertmessage = message()) echo "<script type='text/javascript'>alert('{$alertmessage}');</script>";

Then you'll only get the alert if there's a message to show

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top