Php echo javascript alert () not working
I want to display a popup message when the user is logged out, so I use
echo "<script>alert(\"You are logged out\");</script>";
But that won't work.
Below is my coding. Is there some kind of logical problem in my coding?
<?php
session_start();
if(isset($_SESSION['Username']) == "admin")
{
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
@import "../CSS/Style.css";
@import "../CSS/Admin.css";
</style>
<title>Admin Home Page</title>
</head>
<body>
<div class="body"></div>
<?php
if(isset($_GET['id']) == "logout")
{
session_destroy();
echo "<script>alert(\"You are logged out\");</script>";
header("Location: ..\Main.php");
}
else
{
?>
<div class="menu">
<a href="ManageStaff.php">Manage Staff</a>
</div>
<div class="menu2">
<a href="ManageAccount.php">Manage Account</a>
</div>
<div class="logout">
<a href="AdminHomePage.php?id=logout">Logout</a>
</div>
<?php
}
}
else
{
?>
<center>
<p style="font-size:50px; font-weight:bold">Access Denied</p>
<p style="font-size:18px">Your request for this page has been denied because of access control</p>
</center>
<?php
}
?>
</body>
</html>
The session will be destroyed and will also be redirected to Main.php, but alert()
it will not exit.
source to share
You echo and then record the title move. If you have moved to javascript (after the user has clicked the alert) it will probably work as you expect.
echo "<script>alert('You are logged out'); window.location.href='..\Main.php';</script>";
Also, the way you are using isset
will cause problems because it isset
returns true or false (it checks if a value is present) instead of returning a value.
So instead of
if(isset($_SESSION['Username']) == "admin")
You need to do:
if(isset($_SESSION['Username']) && $_SESSION['Username'] == "admin")
source to share
header("Location: ..\Main.php");
tells the browser to navigate to another page before even displaying the page ... if you want the user to see the warning try this:
session_destroy();
echo "<script>";
echo "alert('You are logged out');";
echo "window.location = '../Main.php';"; // redirect with javascript, after page loads
echo "</script>";
source to share
use this it will solve your problem !! first change your code from
if(isset($_SESSION['Username']) == "admin")
{
to
if(!empty($_SESSION['Username']) && ($_SESSION['Username']=="admin")){
and use the following code
if(!empty($_GET['id']) && ($_GET['id']=="logout"))
{
session_destroy();?>
<script>
alert("You are logged out");
window.location.href='..\Main.php';
</script>
<?php }?>
source to share