www.webdeveloper.com
Results 1 to 12 of 12

Thread: Ajax and PHP Sessions

  1. #1
    Join Date
    Jan 2007
    Posts
    54

    Question Ajax and PHP Sessions

    Okay, here's the set up:

    When a user submits their login info, Ajax carries it off to the .php file that verifies the credentials. After the credentials are verified, php initiates a sessions and assigns user info to the session variables. Once these steps have been completed successfully the .php file will send back either a 1(success) or 0(failure) back to the login page. The login page then proceeds to greet the user, with their username that was stored in $_SESSION['un'].

    Now, here's the problem:

    After the ajax call is completed the session is completely empty. Does the page need to be refreshed in order to see the new session variables?

    I looked this problem up, and I kept running into the phrase "race conditions," after reading what this was, I determined that it couldn't be the problem because only 1 ajax call was made, and the main page doesn't try to read the session variables until after the ajax call is completed.

    Does anyone have insight on this? I'd appreciate a solution. Thanks in advanced!

  2. #2
    Join Date
    Sep 2008
    Location
    Tel Aviv, Berlin, L.A.
    Posts
    165

    Not race, but STATE

    The problem that you point to is a classic "AJAX-one".

    Consider this: You'll be able to invoke ANY AJAX call NOT before onload() (html body event) has been fired. So, what you see on your page is all (neither less nor more) that has been processed until HERE (no matter whether $_POSTs, $_GETs, environmental or session vars.)

    The AJAX call you invoke to handle the user's logon data is (as the name [A]synchronous [J]avascript [A]nd [X]ML suggests) asynchronous, which at least enables your form(s) to "falling back to work".

    Now, as I assume, a given process triggered by a given method call checks, approves/declines the user and sets or updates session vars, respectively. If you immediately lookup those vars, you have to RETRIEVE them - you wrote: "The login page then proceeds to greet the user, with their username that was stored in $_SESSION['un'].." - Proceeds how? And, more importantly, to where?

    This is a question of STATE (race conditions more or less focus on the execution of several AJAX calls at a time, where it is not clear, which call returns first, thus circuits or non-resolvable independencies occur), and you need to take care just of the state (in web applications this is simply the next completed onload() event.

    If you don't want to RE-LOAD (which I guess, cos this is usually the reason for an AJAX call) you have an easy workaround:

    a) hold some fields that may assume the value of a given session var, make them invisible at load time.
    b) when the AJAX call returns (which it usually does within a script of JavaScript), populate those (still hidden) fields with the returned values and make them visible. - The thing is that your session vars are -of course!- already set. And this is actually the important part. Now, if you want to share that info with the user, you just "pass" the values to some fields which CAN be modified (getElementById()... value =....) AFTER onload(), thus avoiding a RE-LOAD.

    Best from the south.

  3. #3
    Join Date
    Jan 2007
    Posts
    54
    I appreciate the help, but that was too verbose for me to actually see if there was a answer to my original question in there.

    Simplified...

    If you set session variables in the .php file that you make the request to, will you have access to those variables in the file that made the request when the the status of the request.readyState is 4 and request.status is 200?

  4. #4
    Join Date
    Jan 2007
    Posts
    54
    I suppose I'll take this over the Javascript forum and see if anyone can help.

  5. #5
    Join Date
    Sep 2008
    Location
    Tel Aviv, Berlin, L.A.
    Posts
    165
    If you'd post the JS function that invokes the AJAX call, I can show you how to proceed from there.

    Best from the south.

  6. #6
    Join Date
    Jan 2007
    Posts
    54
    Code:
    function login() {
      var myurl = '/admin/includes/login.php';
      myRand = parseInt(Math.random()*999999999999999); 
      http.open("POST", myurl, true);
      http.onreadystatechange = useHttpResponse;
      var usnm = document.getElementById('un').value;
      var pswd = document.getElementById('pw').value;
      http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      http.send("un=" + usnm + "&pw=" + pswd + "&rand=" + myRand);
    }
    
    function useHttpResponse() {
       if (http.readyState == 4) {
        if(http.status == 200) { 
    		document.getElementById('loading').innerHTML = '';
    		//
    		//Session was set in the http request
    		//$_SESSION['id'] should be set
    		//
    		alert('<?php echo $_SESSION['id']; ?>');
        }
      } else {
      document.getElementById('loading').innerHTML = '<h1>Loading...</h1>';
      }
    }
    Here's the requested file:

    PHP Code:
    <?php

    require($_SERVER['DOCUMENT_ROOT'] . '/admin/includes/config.php');

    $un trim($_REQUEST['un']);
    $pw trim($_REQUEST['pw']);
    mysql_real_escape_string($un);
    mysql_real_escape_string($pw);
    $cpw crypt($pw,'$salt');
    $q "SELECT password, registered FROM users WHERE username = '$un'";
    $result mysql_query($q);
    $row mysql_fetch_array($result);
    $dbpw $row['password'];
    $dbrg $row['registered'];
    if(
    $cpw == $dbpw && $dbrg == 1) {
        
    $q "SELECT * FROM users WHERE username = '$un'";
        
    $result mysql_query($q);
        while (
    $row mysql_fetch_array($result)) {
            
            
    $Session = new Session();
            
    $Session->start($row['userid'], $row['username'], $row['emailaddress'], $row['fname'], $row['lname'], $row['usertypeid']);
            
            echo 
    1;
        }
    } else {
        echo 
    0;
    }

    ?>

  7. #7
    Join Date
    Jan 2007
    Posts
    54

    [resolved]

    Seeing as how the PHP is ran before all of the Javascript, this can't be done how I'm asking. I've found another way to accomplish a similar effect. Thanks for the effort. Much appreciated!

  8. #8
    Join Date
    Sep 2008
    Location
    Tel Aviv, Berlin, L.A.
    Posts
    165
    Oh, done. Good. Well, sorry for being late, but I had absolutely no time to drop by yesterday. However, great to hear that you've found a solution anyways.

    Best from the south.

  9. #9
    Join Date
    Jun 2006
    Location
    Down at the bottom of the garden
    Posts
    1,239
    Code:
    mysql_real_escape_string($un);
    mysql_real_escape_string($pw);
    Should be..
    Code:
    $un = mysql_real_escape_string($un);
    $pw = mysql_real_escape_string($pw);

  10. #10
    Join Date
    Sep 2008
    Location
    Tel Aviv, Berlin, L.A.
    Posts
    165
    Where I don't get whom you're quoting here...

  11. #11
    Join Date
    Jun 2006
    Location
    Down at the bottom of the garden
    Posts
    1,239
    Quote Originally Posted by ariell View Post
    Where I don't get whom you're quoting here...
    http://www.webdeveloper.com/forum/sh...61&postcount=6

  12. #12
    Join Date
    Sep 2008
    Location
    Tel Aviv, Berlin, L.A.
    Posts
    165
    I'm probably too stupid, but as I understand, this quote is in no way related to the thread's topic.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles