Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm facing a head messing situation while retrieving PHP SESSION details via ajax and jQuery.

Let me explain the whole situation.

My fetch.php [get and send the SESSION details]:

 header('Content-Type: application/json');
 session_name('admin');
 session_set_cookie_params(2*7*24*60*60);
 session_start();
 echo json_encode(array(
   'session'=>$_SESSION,
   'session'=>array(
     'user'=>$_SESSION['user'],
     'email'=>$_SESSION['email'],
     'rememberMe'=>$_SESSION['rememberMe']
   ),
 ));
 exit(0);

jQuery code to fetch the details :

 $.ajax({
   url: "fetch.php",
   type: "get",
   dataType: 'json',
   cache: false,
   success: function(data){
     user = data.session.user;
     email = data.session.email;
     rememberMe = data.session.rememberMe;
   }
 });

After fetching, I'm trying to add/remove something to my html [based on the session details]:

 if(user != null && user != undefined && user != "undefined"){
   //if 'user' is not 'null/undefined', it means that he is logged in, so add something
 }else{
   //remove the added item
 }

MAIN PHP :

 header('Content-Type: application/json');
 session_name('admin');
 session_set_cookie_params(2*7*24*60*60);
 session_start();

 if($_SESSION['user'] && !isset($_COOKIE['remember']) && !$_SESSION['rememberMe']){
   $_SESSION = array();
   session_destroy();
 }  

 //......

 if($_REQUEST['Login']){
   // ....
   $_SESSION['user']=$name;
   $_SESSION['email']=$email;
   if(isset($_POST['rememberMe'])){
     $_SESSION['rememberMe'] = $_POST['rememberMe'];
     setcookie('remember',$_POST['rememberMe']);
   }else{
     setcookie('oneTime','1');
   }
   // ....
 }

 //.......

 if($_REQUEST['Logout']){
   $_SESSION = array();
   session_destroy();
   $admin['msg'] = "Logout successful";
 }

Now, the main problem is, this code behave mysteriously/unpredictable... for testing purpose, I add

  alert(user);

just after my ajax code.

So, When I load the page, it alerts undefined, its good. But when I logged-in successfully {for example, logging-in with "try" user} it alerts null rather than the user name, and add the dynamic element to the html. It means, totally ignoring the if condition.

And when I refresh the page without logging-out, it alerts undefined and didn't remove the dynamically added element.

While I logout the user, it alerts the real user name {"try"} and remove the dynamically added elements [again, ignoring the if condition].

here is my jQ "login" code:

 $.ajax({
   url: $frm.attr('action')+'?'+name+'=true',
   type: $frm.attr('method'),
   data: serial,
   success: function(response){
     //.....
   }
 });

can somebody tell me that where i'm doing wrong....

And sorry for typo OR grammatical mistakes.

UPDATE:

some code from my main.js:

 var handler = {
   init: function(){
     $.ajax({
       url: "fetch.php",
       type: "get",
       dataType: 'json',
       cache: false,
       success: function(data){
         user = data.session.user;
         email = data.session.email;
         rememberMe = data.session.rememberMe;
       }
     });
     alert(user);  // echoing the value of user
     if(user != null && user != undefined && user != "undefined"){
       //....... dynamically add the element is user is logged-in
     }else{
       //...... remove the dynamically added element
     }
     handler.submit();
   },
   submit: function(){
    $('html').on('click','.submit',function(e){
       var $frm = $(this).parents('form');
       var serial = $frm.serialize();
       var name = $(this).attr('name');
       $.ajax({
         url: $frm.attr('action')+'?'+name+'=true',
         type: $frm.attr('method'),
         data: serial,
         success: function(response){
             //....... on success : some code
         }
       });
       setTimeout(function(){handler.init();},5000);
       e.preventDefault();
     });
   }
 };
 $(document).ready(handler.init);
share|improve this question
    
What's the first if in your main.php for? Also could you explain the sequence of when your ajax is being called? This may have something to do with the order of the code execution. Eg. -> Your ajax called first before the login code executed –  I Can Has Kittenz Mar 25 at 10:59
    
in "main.php", the first "if" is to check the the session is avab with "rememberMe" [if($_SESSION['user'] && !isset($_COOKIE['remember']) && !$_SESSION['rememberMe']){ $_SESSION = array(); session_destroy(); }] for main ajax, let me update the question and thanks for replying –  Nikita Chaudhary Mar 25 at 11:21
    
It's quite possible that the only reason you are getting null when alerting the value of 'user' is that AJAX is asynchronous, meaning your alert won't wait for the AJAX call to finish before executing and neither will your if() statement - try moving both to within the success callback of your AJAX call and see what happens –  Keir Lavelle Mar 25 at 11:41
    
I just put the fetching code into the success function, now its works good, but dear here is another situation to do this is : the dynamically adding a element is not working until I logged in again. It means that the "rememberMe" option is not working when page is refreshed –  Nikita Chaudhary Mar 25 at 11:48
    
so, I must have to put the fetching code somewhere in a function that called when "document is ready", so that the logged-in user remains logged-in and can access the dynamic content. –  Nikita Chaudhary Mar 25 at 11:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.