1

I am trying to print alert when user is redirected to login-redirect, however the alert isn't working as I want it to, instead it brings the user straight to the login-redirect.

Here's my code:

<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<?php 
session_start();

if( !isset($_SESSION["loginSuccess"]) ){
   echo "<script type='text/javascript'>alert('Login failed!');</script>";
   header('Location:' . $base_url . 'login-redirect');
}
?>
5
  • 2
    Possible duplicate of How to fix "Headers already sent" error in PHP Commented Oct 9, 2015 at 10:16
  • You must place first session_start(); before outputting something on your page. So place session_start(); before outputting html like jquery script tag. Commented Oct 9, 2015 at 10:17
  • 1
    "Javascript alert not running in PHP" Whew! That's a relief. :-) Commented Oct 9, 2015 at 10:19
  • Do not echo or print anything before header Commented Oct 9, 2015 at 10:20
  • You cannot run Javascript and then expect a redirect header to work. If you must do these two things together, use a Javascript redirect instead. Commented Oct 9, 2015 at 11:58

2 Answers 2

1

That's just how it works. You're doing a redirect, but it doesn't run the js before redirecting. If you want to run the js then you'll need to do the redirect different using a meta tag or JavaScript, rather than a http header.

Sign up to request clarification or add additional context in comments.

Comments

0

The alert is working.

I think your session variable is not set.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.