Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I need to set PHP session variable or change is to "" or get it via javascript . for some reason the variables are not set and not get . Can the javascript there are any restrictions on this? Here is the sample code:

JS (get variable):

function getSessionVariable(variable){
if(typeof variable=="string"){
    var xhttpSession = new XMLHttpRequest();
    xhttpSession.open('POST','session.php',false);
    xhttpSession.onreadystatechange= function(){
        if(xhttpSession.readyState==4 && xhttpSession.status==200){
            return xhttpSession.responseText;
        }
    }
    xhttpSession.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xhttpSession.send("sessionValue="+variable+"&command=get");
}

JavaScript code above gets a normal result, which shows by the debugger, but for some reason the variables which are assigned for example function getSessionVariable('userName') is undefined (despite the fact that the debugger shows such as "return = 'Bob' ")

session.php

if(isset($_REQUEST['command']) && $_REQUEST['command']=='get' && 
isset($_REQUEST['sessionValue'])){

    $value = $_REQUEST['sessionValue'];
    $res = $_SESSION[$value];
    echo ($res);
}

Same thing when changing values:

function logInCheck(){
var userName = getSessionVariable('userName');
if(document.getElementById('name').value!= userName && userName!=undefined){
    if(getCookie('logined')=="true"){
        var xhttpSession = new XMLHttpRequest();
        xhttpSession.open('POST','session.php',true);
        xhttpSession.onreadystatechange = function(){
            if(xhttpSession.readyState==4 && xhttpSession.status==200){
                xhttpSession.abort();
            }
        }
        xhttpSession.send("command=end")}
    }

session.php

if(isset($_REQUEST['command']) && $_REQUEST['command']=="end" && isset($_REQUEST['userName'])){
    $userName =  $_REQUEST['userName'];
    $result = mysql_query('SELECT user_id FROM users WHERE userName="{$userName}"');
    $row = mysql_fetch_array($result);
    $user_id =$row['user_id'];
    mysql_query("DELETE FROM userlist WHERE user_id= '{$user_id}'");
    $_SESSION['userName']="";
    $_COOKIE['logined']="";
}

Thanks in advance for any help.

share|improve this question
3  
These seems horrendously insecure to be exposing session variables to the client in this manner. –  Mike Brant Sep 17 '14 at 18:34
    
do you have session_start() on the first line after the opening php tag in session.php? –  Len_D Sep 17 '14 at 20:17
    
@Len_D Yes I have –  Deodat Teos Sep 17 '14 at 20:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.