Data loss in session

Asked

Viewed 137 times

2

I’m making a form with steps in Ajax. The idea is to each step take the form data, play an array and store the array in the session, so I can manipulate all the data in the last step:

Ajax formulario1:

$('.next').click(function(){
   $.post({
      url: '/teste_mvc/turma/step1/' ,
      data: $('#step1').serialize(),
      success: function (e){alert(e);}
});

Action step1

public function Step1(){
    session_start();
    $ses = array();
    foreach($_POST as $k=>$p){
        $ses[$k] = $p;
    }
    $_SESSION['step1'] = $ses;
    print_r($_SESSION['step1']);
    exit;
}

So far the application works as it should, problem is with the second step forward:

Ajax formulario2:

 $('.next').click(function(){
     $.post({
         url: '/teste_mvc/turma/step2/' ,
         data: $('#step2').serialize(),
         success: function (e){alert(e);}
      });
 });

Action step2

 public function Step2(){
    session_start();
    $ses = array();
    foreach($_POST as $k=>$p){
        $ses[$k] = $p;
    }
    $_SESSION['step2'] = $ses;
    print_r($_SESSION['step1']);
    print_r($_SESSION['step2']);
    exit;
}

When returning session data back to ajax the value of $_SESSION['step2'] PHP can recover, but the $_SESSION['step1'] are lost, with PHP returning undefined for her.

I must be making a silly mistake, but I’m trying to make it work here and everything I know has been applied.

  • These foreach to go through the $_POST array are unnecessary, for that it was enough $_SESSION['step1'] = $_POST;

  • @Miguel I already solved this problem, is that I created a custon mvc for the project and was tending to leave the global session. It was enough to call the session with each request that the data was not lost anymore

  • This wasn’t the point of the question, it’s just to point out that redundancy in your code

1 answer

0


The problem in the code is quite simple and really is silly, you are restarting the sessions, the session_start() should be used only 1 time. You can much call it at the beginning of the code. Strongly do not recommend using it within a function!

Solution: What you may be doing and why session_start() out of functions, starting only once. At the beginning of the code preferably!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.