PHP and AJAX Session not persisting.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dgourd
    New Member
    • Apr 2010
    • 25

    PHP and AJAX Session not persisting.

    I have a a PHP script that does all the logging in and creating session. I also have some javascript that uses AJAX to make a request to the PHP script and return the response. The problem I run into is that the session is being set, but as soon as I go to a different page or refresh, the session data goes away. Here are my scripts:

    login.php:
    Code:
    <?php
    
        session_start();
        
        // Initializing variables
        $user_info;
        $username;
        $password;
        $errors_login = array();
        $response = "";
        
        if ($_POST['login_button'] == 'submit') {
            // If the submit button was pressed
            
            if (isset($_POST['username'])) {
                // If they entered a username, set variable
                $username = $_POST['username'];
            } else {
                // If they didn't enter a username, create an error
                $errors_login[] = "Please enter your username";
                unset($username);
            }
            
            if (isset($_POST['pass'])) {
                // If they entered a password
                $password = SHA1($_POST['pass']); // The password is always encrypted
            } else {
                // If they didn't enter a password, create an error
                $errors_login[] = "Please enter your password";
                unset($password);
            }
            
            if (isset($username) && isset($password)) {
                // If everything above was successfull, find the user and store the data in a session
                include('../mysqli_connect.php');
                
                $query = "SELECT * FROM members WHERE username = '$username';";
                $q = mysqli_query($dbc, $query);
                if (mysqli_affected_rows($dbc)) {
                    // If there is a person with that username
                    $user_info = mysqli_fetch_array($q, MYSQLI_ASSOC);
                    if ($password == $user_info['pass']) {
                        // If the passwords match
                        if (isset($user_info['status'])) {
                            
                            // If the person has confirmed their email address
                            $_SESSION['id'] = $user_info['user_id'];
                            $_SESSION['f_name'] = $user_info['first_name'];
                            $_SESSION['l_name'] = $user_info['last_name'];
                            $_SESSION['username'] = $user_info['username'];
                            $_SESSION['status'] = $user_info['status'];
                            
                            // If all the sessions are set, create their easier variables
                            $id_login = $_SESSION['id'];
                            $f_name_login = $_SESSION['f_name'];
                            $l_name_login = $_SESSION['l_name'];
                            $username_login = $_SESSION['username'];
                            $status_login = $_SESSION['status'];
                        } else {
                            // The person has not confirmed their email
                            $errors_login[] = "Please confirm your email address";
                        }
                    } else {
                        // The passwords don't match
                        $errors_login[] = "Your password is incorrect";
                    }
                } elseif (mysqli_affected_rows($dbc) == 0) {
                    // If nobody with that username was found
                    $errors_login[] = "Your username is incorrect or you haven't registered";
                } else {
                    // Some unknown mysql error occured
                    $errors_login[] = "There was an error contacting the database";
                }
                mysqli_close($dbc);
            }
            
            if ($errors_login != NULL) {
                // If there are any errors
                
                $response .= '<h3>Members</h3>';
                $response .= '<p>Errors:</p>';
                $response .= '<ul class="sidebar_menu">';
                foreach ($errors_login as $value) {
                    $response .= '<li>' . $value . '</li>';
                }
                $response .= '</ul>';
                $response .= '<br />';
                
                // Display the form
                $response .= '<input type="hidden" id="login_button" value="submit" />';
                $response .= '<input type="text" id="username" value="Username" class="loginfield" maxlength="60" onfocus="clearText(this)" onblur="clearText(this)" /><br />';
                $response .= '<input type="text" id="pass" value="Password" class="loginfield" maxlength="60" onfocus="clearText(this)" onblur="clearText(this)" /><br />';
                $response .= '<input type="submit" id="login_submit" value="Submit" class="loginbutton" title="Submit" onclick="updateLogin()" />';
                $response .= '<img alt="AJAX Loading" src="images/ajax-loader.gif" id="ajax_loader" style="display:none" />';
                $response .= '<div class="cleaner"></div>';
                echo $response;
            } else {
                // Display the hello sign
                $response .= '<h3>Members</h3>';
                $response .= '<p>Welcome!</p>';
                $response .= '<p>You are currently logged in ' . $f_name_login . ' ' . $l_name_login . '!</p>';
                $response .= '<input type="hidden" id="login_button" value="logout" />';
                $response .= '<input type="submit" id="login_submit" value="Logout" class="loginbutton" title="Logout" onclick="updateLogin()" />';
                $response .= '<img alt="AJAX Loading" src="images/ajax-loader.gif" id="ajax_loader" style="display:none" />';
                $response .= '<div class="cleaner"></div>';
                echo $response;
            }
        } else if ($_POST['login_button'] == 'logout') {
            session_destroy();
            $response .= '<h3>Members</h3>';
                $response .= '<input type="hidden" id="login_button" value="submit" />';
                $response .= '<input type="text" id="username" value="Username" class="loginfield" maxlength="60" onfocus="clearText(this)" onblur="clearText(this)" /><br />';
                $response .= '<input type="text" id="pass" value="Password" class="loginfield" maxlength="60" onfocus="clearText(this)" onblur="clearText(this)" /><br />';
                
                $response .= '<input type="submit" id="login_submit" value="Submit" class="loginbutton" title="Submit" onclick="updateLogin()" />';
                $response .= '<img alt="AJAX Loading" src="images/ajax-loader.gif" id="ajax_loader" style="display:none" />';
                $response .= '<div class="cleaner"></div>';
                echo $response;
        } else {
            // If the submit or logout button was never pressed
            if (isset($id_login, $f_name_login, $l_name_login, $username_login, $status_login)) {
                // If all the sessions are set
                // Display the hello sign
                $response .= '<h3>Members</h3>';
                $response .= '<p>Welcome!</p>';
                $response .= '<p>You are currently logged in ' . $f_name_login . ' ' . $l_name_login . '!</p>';
                $response .= '<input type="hidden" id="login_button" value="logout" />';
                $response .= '<input type="submit" id="login_submit" value="Logout" class="loginbutton" title="Logout" onclick="updateLogin()" />';
                $response .= '<img alt="AJAX Loading" src="images/ajax-loader.gif" id="ajax_loader" style="display:none" />';
                $response .= '<div class="cleaner"></div>';
                echo $response;
            } else {
                // The sessions are not set
                $response .= '<h3>Members</h3>';
                $response .= '<input type="hidden" id="login_button" value="submit" />';
                $response .= '<input type="text" id="username" value="Username" class="loginfield" maxlength="60" onfocus="clearText(this)" onblur="clearText(this)" /><br />';
                $response .= '<input type="text" id="pass" value="Password" class="loginfield" maxlength="60" onfocus="clearText(this)" onblur="clearText(this)" /><br />';
                $response .= '<input type="submit" id="login_submit" value="Submit" class="loginbutton" title="Submit" onclick="updateLogin()" />';
                $response .= '<img alt="AJAX Loading" src="images/ajax-loader.gif" id="ajax_loader" style="display:none" />';
                $response .= '<div class="cleaner"></div>';
                echo $response;
            }
        }
    ?>
    javascript:
    Code:
    window.onload = main;  // Setting the onload handler to main() function
            
    function main() { // Creating the main function that calls other scripts
                
        // Creating the XMLHttpRequest object
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        
    }
    
    function updateLogin() {
        
        var url = "login.php";
        var id = "login_form";
        var button = document.getElementById("login_submit");
        var loader = document.getElementById("ajax_loader");
        var params = "";
        
        button.style.display = "none";
        loader.style.display = "";
        
        var nodes = document.getElementById(id).childNodes;
        for (var j = 0; j < nodes.length; j++) {
            if (nodes[j].tagName == 'INPUT') {
                params += nodes[j].id + "=" + nodes[j].value + "&";
            }
        }
        
        // Open a new AJAX connection
        xmlhttp.open("POST", url, true);
    
        //Send the proper header information along with the request
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");
        
        // Setting what to do on ready state change
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                document.getElementById(id).innerHTML = xmlhttp.responseText;
            }
        }
        
        // Sending the parameters
        xmlhttp.send(params);
        
    }
    
    function clearText(field) {
    
        // Toggles between the default value and the empty string
        if (field.defaultValue == field.value) {
            field.value = '';
            if (field.id == 'pass') {
                field.type = "password";
            }
        }
        else if (field.value == '') {
            if (field.id == 'pass') {
                field.type = "text";
            }
            field.value = field.defaultValue;
        }
    }
  • oranoos3000
    New Member
    • Jan 2009
    • 107

    #2
    hi
    for use session variable in pages
    1-you must type session_start before any statement in script or you must set session.auto_st art to 1
    2-if your request is send by a ajax function and result is return , in this ajax code you must add appropriate part .

    be successful

    Comment

    • dgourd
      New Member
      • Apr 2010
      • 25

      #3
      Thanks for the response oranoos3000,
      1. I did use session_start() on line 3 of login.php
      2. I dont understand what you mean by 'appropriate part'. I made login.php echo back the html and the AJAX function uses innerHTML to put the response on the page.


      I did do an echo "$_SESSION['username']"; statement before and at the end of the AJAX function, it would return the correct variable, so I know that the session was set. The problem is when I refresh the page it disappears.

      Comment

      • dgourd
        New Member
        • Apr 2010
        • 25

        #4
        So I used the same php code, modified a little bit to format correctly but basically the same, and took out the AJAX function. The same problem still occurs so I am sure something is wrong with my login.php, but I don't know what.

        Comment

        • dgourd
          New Member
          • Apr 2010
          • 25

          #5
          I solved the problem. I have a header.php file that is included at the top of every page. I did a check to see if one of the sessions was set. If it wasn't, I explicitly set it to NULL.

          Code:
          if (!isset($_SESSION['id'])) {
              $_SESSION['id'] = NULL;
              $_SESSION['f_name'] = NULL;
              $_SESSION['l_name'] = NULL;
              $_SESSION['username'] = NULL;
              $_SESSION['status'] = NULL;
          }

          Comment

          Working...