A.V
A.V

Reputation: 141

Message is not displayed

My problem is that the message is not displayed when the password and the username are correct. Then my page go on foredeck.php . This part is good but why my message is not displayed before it change web page ? In the case of the password or the unsername is not correct the second message appear. I have a problem just with the first : echo "alert('Connexion Réussite')";

 <?php
    $msg = '';

    if (isset($_POST['login']) && !empty($_POST['username']) 
       && !empty($_POST['password'])) {

       if ($_POST['username'] == 'foredeck' && 
          $_POST['password'] == 'foredeck1') {
          $_SESSION['valid'] = true;
          $_SESSION['timeout'] = time();
          $_SESSION['username'] = 'tutorialspoint';
               $msg ='Connexion Réussite';
          echo $msg= "<script type='text/javascript'>alert($msg)</script>";

         header("location: foredeck.php");

       }else {
          $msg='Identifiant ou Mot de Passe incorrecte';
          $msg =  "<script type='text/javascript'>alert('$msg')</script>";
       }
    }
 ?>

Upvotes: 0

Views: 81

Answers (3)

affaz
affaz

Reputation: 1191

The PHP header(location) is executed before alert() which is JS,so the alert is not being displayed and the page gets redirected. So use window.location in <script>(redirect code in JS) instead of header(location)

  <?php
      $msg = '';

      if (isset($_POST['login']) && !empty($_POST['username']) 
         && !empty($_POST['password'])) {

         if ($_POST['username'] == 'foredeck' && 
            $_POST['password'] == 'foredeck1') {
            $_SESSION['valid'] = true;
         $_SESSION['timeout'] = time();
         $_SESSION['username'] = 'tutorialspoint';
         echo "<script type='text/javascript'>alert('Connexion Réussite');
window.location.href='foredeck.php';
</script>";



      }else {
         $msg =  "<script type='text/javascript'>alert('Identifiant ou Mot de Passe incorrecte')</script>";
      }
   }
   ?>

The alert will be shown first and redirected when pressed ok..

Upvotes: 2

adnanoswd
adnanoswd

Reputation: 28

Basically, Javascript runs on the browser and PHP runs on the server, so the code work step by step as you are expecting here. Here the PHP code runs before the javascript code which is the reason that you would get redirected before JS code runs.

You can solve this by:

  • Removing the header(location: foredeck.php).
  • and putting window.location = 'foredeck.php'; in the javascript.

This will make your alert work first and then redirect it to the foredeck.

Upvotes: 1

node_modules
node_modules

Reputation: 4925

The problem is because the header() will execute the redirection immediately. Use the header refresh with a timer like this:

 header("refresh:5; url=wherever.php");

I hope this will help you!

Upvotes: 0

Related Questions