0

I'm sending an Ajax request which sends an object objectVariable to a PHP file:

$.post(url, {action : 'function' , object : objectVariable });

Then, the PHP file will store objectVariable in $_SESSION['objectVariable'] (I'm omitting validation to make it clear):

function function_callback() {

    if(!session_id()) 
        session_start();

    $_SESSION['objectVariable'] = $_POST['objectVariable'];
}

When the user goes to other page of the site, the $_SESSION['objectVariable'] will be sent from PHP to the user by Ajax again. Here, I should encode the array stored in $_SESSION['objectVariable'] to a JSON string:

//inside other Axax callback function
echo json_encode($_SESSION['objectVariable']);

That's working right, but I also could store a JSON string into $_SESSION['objectVariable']:

function function_callback() {

    if(!session_id()) 
        session_start();

    $_SESSION['objectVariable'] = json_encode($_POST['objectVariable']);
}

And after, just echo $_SESSION['objectVariable'] to send it to the Javascript file.

I wonder what would be a better way: store an array in $_SESSION['objectVariable'], or store a JSON string.

Any suggestion about it?

1 Answer 1

1

When sending data between Javascript/PHP I always keep it encoded as a JSON string. It makes things simpler. In fact, I would just JSON.stringify() it right away when you send it to the server the 1st time.

This way you also will always know what type the data will be.

Sign up to request clarification or add additional context in comments.

1 Comment

Using objects makes validation more simply in my case. Anyway, I decided to use a string to store it in $_SESSION. Thanks for your suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.