2

I am using cakePHP 1.26.
In a controller, I got a function which contains these lines of code:

$this->Session->write('testing', $user);
$this->Session->read('testing');

Now the system wrote a session and stored on the server. Is it possible to use Javascript or Jquery to read the session named 'testing' ?

6 Answers 6

9

The PHP session is stored in webserver's memory while JavaScript runs in the webclient (webbrowser). Those are in real world two physically separate and independent machines. They usually can only communicate with each other over network using HTTP protocol.

You have 2 options:

  1. Let PHP print the session data as if it's a JS variable:

    <script>var data = '<?= $_SESSION['data'] ?>';</script>
    
  2. Let JS request it from the server end using Ajax. Here's a jQuery based example:

    <script>$.get('script.php', function(data) { /* .. */ });</script>
    

    with basically this in script.php:

    <?php echo $_SESSION['data']; ?>
    

Needless to say that option 1 is the most easy and straightforward.

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

Comments

1

No. Generally, you could write the value of testing into the document delivered to the client (a small javascript in the head perhaps?), and then it would be available to the client end.

Comments

1

As other people have already said, getting the session at the client side requires some forethought (blurting it out on the page) or another request.

The other solution is not to use a session but use cookies instead or as a compliment. Just don't trust the cookies. Users can edit them so they should only be used for display stuff.

Comments

1

Is it possible to use Javascript or Jquery to read the session named 'testing' ?

No, but you can use PHP to put the value into javascript:

<?php
print "<script type=\"text/javascript\">\n";
print " var testing=\"" . $_SESSION['testing'] / "\";\n";
print "</script>\n";
?>

(or into the HTML and read it back from there using Javascript)

Comments

0

No. You can use JavaScript to make an AJAX get request to a PHP page that would read the session data and return to the JavaScript.

Comments

0

You can easily pass the session variable from the PHP server using jQuery AJAX to the JavaScript. You can pass it as Json object and then assign it to a JavaScript variable.

Comments

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.