Reputation: 105
I am using jquery ajax to set sessions on loggin but for some reason, the session is not set unless I refresh the page which beats the purpose of ajax. I dont know how i can resolve this. Here is my code: $("#signin").click(function(){ 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);
?>
Upvotes: 1
Views: 396
Reputation: 15835
jquery ajax is asynrounous which happens paralley , so you cannot expect it to be complemeted in sequence , so have your logic in the call back which ensures the ajax call is completed.
I am giving some sample code below.
$.ajax({
url: "test.html",
context: document.body,
success: function(){
**write your session related logic here**
}
});
Upvotes: 2