Skip to content
Advertisement

PHP – Can’t log out and show alert message at the same time

I have a PHP login system where you can delete your account/profile if you’d like to. When the user clicks on the button I want them to be logged out, their account to be deleted and an alert message (JavaScript) saying that their account has been deleted. The problem is that the alert message doesn’t appear when I include the logout.php file. If I remove that line of code the alert message appears, but the user will still be logged in. How can I fix this?

Here is my code.

profile.php:

<form class="form" action="delete.php" method="post">
      <button type="submit" name="delete" value="delete" onclick="return confirm('Are you sure you want to delete your profile?')">Delete profile</button>
    </form>

delete.php:

<?php
session_start();

if (isset($_POST["delete"])) {
  require_once 'dbh.inc.php';

  $deleteUser = "DELETE FROM users WHERE usersId='".$_SESSION["userid"]."'";

if ($conn->query($deleteUser) === TRUE) {
  echo "<script>alert('The profile has been deleted.');</script>";
  include 'logout.php';
} else {
  echo '<script>alert("Something went wrong: ")</script>';
}

} else {
  header("location: ../index.php");
  exit();
}

logout.php:

<?php

session_start();
session_unset();
session_destroy();

header("location: ../index.php");
exit();

Advertisement

Answer

Add redirection along with the alert() in js rather than doing in php.

echo "<script>alert('The profile has been deleted.'); window.location.href='logout.php';</script>";  

This will show alert then redirect to logout.php

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement