title: Set php session via ajax
body: <p>I'm trying to build my AJAX login system but I'm having some problems with PHP sessions.</p>
  
  <p>This is the AJAX code I use in my <code>index.php</code>:</p>
  
  <pre><code>$("#buttonLogin").click(function(){
      $.post("&lt;?php echo $AJAX ?&gt;/ajaxLogin.php",{
          Username : $("#loginUsername").val(),
          Password : $("#loginPassword").val()
      }, 
      function(result){
          if(result == "OK"){
              window.location.href = "&lt;?php echo $PUBLIC?&gt;/home.php";
          } else {
              $("#loginMessageError").show();
          }
      });
  });
  </code></pre>
  
  <p>And this is <code>ajaxLogin.php</code> that is called via AJAX:</p>
  
  <pre><code>&lt;?php
  require_once("../settings.php");
  require_once($ABS_ENGINE."/classUser.php");
  
  $user = new User();
  if($user-&gt;loginUser($_POST["Username"], $_POST["Password"])){
      $UserID = $user-&gt;getUserId($_POST["Username"]);
      session_start();
      $_SESSION['UserID'] = $UserID;
      echo "OK";
  } else {
      echo "ERROR";
  }
  ?&gt;
  </code></pre>
  
  <p>When I'm in <code>home.php</code> and I try to echo <code>$_SESSION["UserID"]</code>, I get the following error:</p>
  
  <blockquote>
    <p>Notice: Undefined index: UserID in C:\xampp\htdocs\webname\resources\templates\headerHome.php on line 23</p>
  </blockquote>
  
  <p>Probably this is not correct because session must be set before any output but if i try to echo <code>$_SESSION['UserID'] = $UserID;</code> line it's session variable is correctly displayed.</p>