使用jquery ajax问题设置会话

时间:2011-02-28 05:25:51

标签: php jquery

我正在使用jquery ajax在loggin上设置会话但由于某种原因,除非我刷新打败ajax目的的页面,否则不会设置会话。我不知道如何解决这个问题。这是我的代码:         $( “#登入”)。点击(函数(){             var email = $(“#loginemail”)。attr('value');

        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);
?>

1 个答案:

答案 0 :(得分:2)

jquery ajax是asynrounous,它发生在paralley中,所以你不能指望它按顺序完成,所以在回调中有你的逻辑确保ajax调用完成。

我在下面提供一些示例代码。

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