January 1, 2012

Set php session via ajax

Question by ShadowBroker

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 the 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:xampphtdocswebnameresourcestemplatesheaderHome.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.

Answer by Starx

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!