I'm trying to build my AJAX login system but I'm having some problems with PHP sessions.
This is the AJAX code I use in my index.php
:
$("#buttonLogin").click(function(){
$.post("<?php echo $AJAX ?>/ajaxLogin.php",{
Username : $("#loginUsername").val(),
Password : $("#loginPassword").val()
},
function(result){
if(result == "OK"){
window.location.href = "<?php echo $PUBLIC?>/home.php";
} else {
$("#loginMessageError").show();
}
});
});
And this is ajaxLogin.php
that is called via AJAX:
<?php
require_once("../settings.php");
require_once($ABS_ENGINE."/classUser.php");
$user = new User();
if($user->loginUser($_POST["Username"], $_POST["Password"])){
$UserID = $user->getUserId($_POST["Username"]);
session_start();
$_SESSION['UserID'] = $UserID;
echo "OK";
} else {
echo "ERROR";
}
?>
When I'm in home.php
and I try to echo $_SESSION["UserID"]
, I get the following error:
Notice: Undefined index: UserID in C:\xampp\htdocs\webname\resources\templates\headerHome.php on line 23
Probably this is not correct because session must be set before any output but if i try to echo $_SESSION['UserID'] = $UserID;
line it's session variable is correctly displayed.
You need to initiate the session first, like session_start().then only you can have the access to session variables. Have a look at this simple example , it might help you:
aj.php
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$.ajax({
type : 'GET',
url : 'sess.php',
data: {
user : 'guna',
},
success : function(data){
alert(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{alert ("Error Occured");}
});
});
</script>
</html>
sess.php
<?php
session_start();
$_SESSION['user']=$_GET['user'];
echo $_SESSION['user'];
?>
As other guys pointed out, better you can also check for session_start() in the page where you reading the session variables.
When I had this kind of problem, the thing that solved it was using exit();
<?php
require_once("../settings.php");
require_once($ABS_ENGINE."/classUser.php");
$user = new User();
if($user->loginUser($_POST["Username"], $_POST["Password"])){
$UserID = $user->getUserId($_POST["Username"]);
session_start();
$_SESSION['UserID'] = $UserID;
echo "OK";
exit();
} else {
echo "ERROR";
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With