Reputation: 122
I know the first thing everyone is going to say is that this has been posted hundreds of times; however, I have tried all the different methods people have suggested with still no luck... I am trying to get an alert message to popup if the login fails but for some reason the message does not want to appear. Here's what I have so far:
if($conn) {
$result=sqlsrv_query($conn, "SELECT * FROM Operator
WHERE Username='{$_POST['login']}'");
$pass=sqlsrv_fetch_array($result);
if($pass["Password"] === $_POST['password']) {
session_start();
$_SESSION['loggedin']=true;
header("Location: home.php");
exit;
}
else {
header("Location: login.php");
echo '<script type="text/javascript">';
echo 'alert("Password Invalid!")';
echo '</script>';
}
}
sqlsrv_close($conn);
The php is working fine but for some reason I can't get the javascript to work. Any ideas?
Upvotes: 0
Views: 33774
Reputation: 3414
Use this code
echo '<script>';
echo 'alert("Password Invalid!");';
echo 'location.href="login.php"';
echo '</script>';
instead of
header("Location: login.php");
echo '<script type="text/javascript">';
echo 'alert("Password Invalid!");';
echo '</script>';
Thanks.
Upvotes: 1
Reputation: 1
there is a missing semicolon right behind the alert:
if($conn) {
$result=sqlsrv_query($conn, "SELECT * FROM Operator
WHERE Username='{$_POST['login']}'");
$pass=sqlsrv_fetch_array($result);
if($pass["Password"] === $_POST['password']) {
session_start();
$_SESSION['loggedin']=true;
header("Location: home.php");
exit;
}
else {
header("Location: login.php");
echo '<script type="text/javascript">';
echo 'alert("Password Invalid!");';
echo '</script>';
}
}
sqlsrv_close($conn);
didnt you check the javscript console ?
EDIT: Sorry, my fault, the semicolon isnt necessary of course.
I testet your php code on my server and it works fine anyway !
Upvotes: 0
Reputation: 2619
i think, the problem is here. you are redirecting the page before the alert message
header("Location: login.php"); /* Redirect browser */
try removing it, or make it redirect after a couple of seconds, like this
header( "refresh:5;url=login.php" ); //redirect after 5 seconds
or you prompt a dialog for the user to click to go to next page. remove the header() tho
<script type="text/javascript">
<!--
var retVal = confirm("Login FAILED! Do you want to continue ?");
if( retVal == true ){
window.location.href = "login.php";
return true;
}else{
alert("User does not want to continue!");
return false;
}
//-->
</script>
Upvotes: 3
Reputation: 1308
Your code that comes after the header doesn't run, maybe try setting a session variable and check for that variable in login.php. You can then call the alert from there, or just show a simple message on the page.
Upvotes: 0
Reputation: 32840
In your code header("Location: login.php");
is there before your js code so it never execute js code it redirects to login page remove it and try.
Upvotes: 1