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:
Better check if session_start() is present in home.php. Without this you will not be able to read the session data.
When you are doing echo $_SESSION['UserID'] = $UserID; you will assigning and accessing at a same line, so it will obviously work.
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";
}
?>