I have a login page that works fine, but it doesn't redirect after the SESSION is set. I want my ajax to display errors if nessesary and redirect if the SESSION was set.
Here is my code:
AJAX:
<script>
function loginUser(){
$.ajax({
type:"post",
url:"process.php",
data:$("#formsubmit").serialize(),
success:function(data){
if($session == true){
window.location.href="http://www.example.com";
}
$("#result").html(data);
}
});
}
</script>
PHP:
if (sha1($passcheck) === $record['password']){
$_SESSION['user']= $_POST['username'];
mysqli_query($db_con, $updateIP);
if($record['admin'] == 1){
$_SESSION['admin1'] = $_POST['username'];
}
}else{
echo "<font color='red'>Username or password was invalid.</font>";
}
if(isset($_SESSION['user'])){
$session = true;
echo $session;
}else{
$session = false;
echo $session;
}
?>
I did not include my whole PHP script or my whole HTML page, because the rest is not useful.
It looks like the problem is that you are trying to use the name of the php variable in your javascript to access the php response.
success:function(data){
if($session == true){
window.location.href="http://www.example.com";
}
$("#result").html(data);
}
The variable $session
isn't defined within the scope of the success
function, thus if($session == true)
will always return false, since $session
will be undefined
.
What ever your PHP code echos will be passed into the success
function using the data
param. Since your PHP code is just echoing either a 0 or 1 you would want to update the if
line to if(data == 1)
, or possibly even just if (data)
since if the data variable is just 0 the it should return false, and if it's 1 then it should return true.
In PHP, when you set a variable to true
and then echo it you get 1
If you set it to false
you get 0
.
You need to set $session
to a string, instead of boolean.
if(isset($_SESSION['user'])){
$session = 'true';
echo $session;
}else{
$session = 'false';
echo $session;
}
And also change
if($session == 'true'){
window.location.href="http://www.example.com";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.