2011-02-28 90 views
1

我正在使用jquery ajax來設置登錄會話,但由於某種原因,會話沒有設置,除非我刷新頁面,以達到ajax的目的。我不知道如何解決這個問題。這裏是我的代碼: $( 「#登入」)點擊(函數(){ 變種的電子郵件= $( 「#註冊郵箱」)ATTR( '值');使用jquery ajax設置會話問題

 var password=$("#loginpassword").attr('value'); 

     if(email==""&&password=="") 
     { 
      $("#loginemail").animate({backgroundColor:"red"},4000); 
      $("#loginpassword").animate({backgroundColor:"red"},4000); 
      return false; 
     } 
     if(email=="") 
     { 
      $("#loginemail").animate({backgroundColor:"red"},4000); 
      return false; 
     } 
     if(password=="") 
     { 
      $("#loginpassword").animate({backgroundColor:"red"},4000); 
      return false; 
     } 
     if(email!=""&&password!="") 
     { 
      var loginemail=$("#loginemail").attr('value'); 

      var loginpassword=$("#loginpassword").attr('value'); 

      $.post("phpfiles/loginvalidation.php",{loginemail:loginemail,loginpassword:loginpassword},function(data){ 
       if(data.success) 
       { 
     $("#theuser").html(data.loggedinuser); 

    $("#loginerror").html("<p>You are logged in.</p>").slideDown(); 

        $("#SignUpandIn").fadeOut(); 

       } 
       else 
       { 
    $("#loginerror").html("<p>Wrong email or password.</p>").slideDown(); 
       } 
      },'json'); 

      return false; 
     } 
    }); 

PHP:。

<?php 
require_once('../Connections/gamesRusconn.php'); 
error_reporting(E_ALL^E_NOTICE); 

if(!isset($_SESSION)) 
{ 
     session_start(); 
} 

mysql_select_db($database_gamesRusconn, $gamesRusconn); 

$emailaddress=$_POST['loginemail']; 

$password=$_POST['loginpassword']; 

$hashedPassword=$password; 

//This query compares login details entered by user against the details in the database. 
$loginSQL=mysql_query("SELECT * FROM customers WHERE EmailAddress='".$emailaddress."' AND CustPassword='".$hashedPassword."'",$gamesRusconn) or die(mysql_error()); 

$customers=mysql_fetch_assoc($loginSQL); 

$loginrows=mysql_num_rows($loginSQL); 

$activeSQL=mysql_query("SELECT * FROM customers ",$gamesRusconn) or die(); 

if($loginrows>0) 
{ 

    $fullname=$customers['FirstName']." ".$customers['Surname']; 

    $email=$customers['EmailAddress']; 

    $_SESSION['loggedInName']= $fullname; 

    $_SESSION['username']=$email; 

    $data['success']=true; 

    $data['loggedinuser']=$fullname; 

} 

elseif($loginrows==0) 
{ 
    $data['success']=false; 

} 
echo json_encode($data); 
?> 

回答

2

jQuery的Ajax是asynrounous恰好paralley,所以你不能指望它在順序complemeted,所以在回調保證了AJAX調用完成你的邏輯。

我給一些示例代碼

$.ajax({ 
    url: "test.html", 
    context: document.body, 
    success: function(){ 
    **write your session related logic here** 
    } 
}); 
+0

有道理,但我將如何在回調方法中分配$ _SESSION變量,因爲它在PHP中看起來像是javascript。請請點亮一些燈。 – John