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');
}
?>
zana
  • 259
  • 2
  • 4
  • 15
  • 2
    Possible duplicate of [How to fix "Headers already sent" error in PHP](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Epodax Oct 09 '15 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. – Indrasinh Bihola Oct 09 '15 at 10:17
  • 1
    *"Javascript alert not running in PHP"* Whew! That's a relief. :-) – T.J. Crowder Oct 09 '15 at 10:19
  • Do not echo or print anything before header – Sunil Pachlangia Oct 09 '15 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. – Simba Oct 09 '15 at 11:58

2 Answers2

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.

Luke Cousins
  • 2,068
  • 1
  • 20
  • 38
0

The alert is working.

I think your session variable is not set.

Pawel Gumiela
  • 1,992
  • 2
  • 20
  • 36
Aman Goyal
  • 46
  • 7