Set php session via ajax

前端 未结 3 1867
心在旅途
心在旅途 2020-12-17 01:07

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:

         


        
相关标签:
3条回答
  • 2020-12-17 01:47

    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.

    0 讨论(0)
  • 2020-12-17 01:49

    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.

    0 讨论(0)
  • 2020-12-17 02:06

    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";
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题