How to get session variables from php server using Ajax function? (PHP HTML JS Ajax)

so in my php i have something like this

$_SESSION['opened'] = true;

But it will not be set to true until the user performs some actions with some other html \ php pages

So I need some kind of Ajax function to be able to get this session variable. And some example of a PHP function to get a variable in a form ready for Ajax to get it.

so I need something in AJAX requesting an action (to some simple php code) that will return a value from $_SESSION.

How to do it?

+3
source share
2 answers

jQuery :

var session;
$.ajaxSetup({cache: false})
$.get('getsession.php', function (data) {
    session = data;
});

getsession.php:

<?php
session_start();
print json_encode($_SESSION);

jQuery AJAX, .

Edit:

:

JS, .

():

var session;
$.ajaxSetup({cache: false})
$.get('getsession.php', {requested: 'foo'}, function (data) {
    session = data;
});

PHP:

<?php
session_start();
if (isset($_GET['requested'])) {
    // return requested value
    print $_SESSION[$_GET['requested']];
} else {
    // nothing requested, so return all values
    print json_encode($_SESSION);
}

$. .

+13

PHP http://my.host/response.php

<?php
session_start();
if(isset($_SESSION['opened']))
    echo "true";
?>

HTML jQuery, :

<script type="text/javascript" src="/path/to/jQuery-x.y.z.js"></script>

:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url:'/response.php',
            cache:false,
            success:function(data){
                // Do something with the result
                if(data=="true"){
                    $('#mydiv').show();
                }else{
                    $('#mydiv').hide();
                }
            }
        );
     });
</script>

myform.php:

<h1>Some Random HTML</h1>
<div id='mydiv' class="<?php if(isset($_SESSION['opened']) && $_SESSION['opened']) echo "hidden_class";?>">
 ...</div>

, JavaScript. / div. - .

+3

Source: https://habr.com/ru/post/1743977/


All Articles