Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set php session via ajax

Tags:

php

session

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.

like image 336
siannone Avatar asked Jan 01 '12 17:01

siannone


2 Answers

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.

like image 114
vkGunasekaran Avatar answered Oct 07 '22 03:10

vkGunasekaran


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";
}
?>
like image 39
Nicola Peluchetti Avatar answered Oct 07 '22 05:10

Nicola Peluchetti