1

I'm not yet a JSON/AJAX master so I don't know how to do this.

I need a $_SESSION['name'] PHP variable to work with in my jQuery stuff and I don't know how to access it... consider:

// the 'who is typing' shindig
    $.ajax(
    {
        url: "whos_typing.html",
        cache: false,
        success: function(whos)
        {   
                // here I need to access $_SESSION['name'] and do stuff with it

            $("#soandso").html(whos); //Insert who's typing into the #soandso       
        }
        });
khaverim
  • 3,386
  • 5
  • 36
  • 46

6 Answers6

12

You'll need to inject it, something like this:

var sessName = '<?php echo $_SESSION['name']?>';

The file containing this script must be executed by the php interpreter (i.e. a .php file)

EDIT: Conceding to Radu's point, it would be safer execute for unsanitized data:

var sessName = <?php echo json_encode($_SESSION['name']) ?>;
Makita
  • 1,812
  • 12
  • 15
  • 5
    Make sure to *always* [`json_encode()`](http://php.net/json_encode) *any* value that will be converted to JavaScript code, otherwise you'll open yourself to [cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting). – rid Aug 11 '12 at 04:24
  • Certainly one should know when to sanitize your data, but I'm not sure if "always use json_encode" is the best advice, maybe "always sanitize"?. For example if the session was already compromised (an issue by itself) and the attacker managed to inject, say something like '+ console.log('hello')+' into the session variable, json_encode would result in "'+ console.log('hello')+'" which would still be executed in the above example. – Makita Aug 11 '12 at 04:55
  • @Makita, it would, for the above example. But the above example is incorrect. You should use `var sessName = ;` which would resolve the issue. And in any case, whatever the variable contains, you definitely should always use `json_encode()`. Not only as a security measure, but also for ensuring that you always obtain working code. What if `$_SESSION['name']` contains, for example, `don't know`? – rid Aug 11 '12 at 06:05
  • @Radu, I try to avoid injection like this in the first place, but if I have to I usually sanitize the data before the echo. In any case point taken and answer updated, thanks. – Makita Aug 11 '12 at 06:25
  • @Radu Wouldn't it be better to validate input to avoid XSS rather than make hacky code in your script to avoid it? It seemms like such a hacky fix, like taking a hammer to something that needs a screw driver – Sammaye Aug 11 '12 at 21:29
  • @Sammaye, there are many legitimate values that will break the JavaScript code unless JSON encoded. XSS avoidance is only a side effect of this. Also, JSON encoding the value somewhere else is out of scope, since you only need to use the value in JavaScript here. JSON encoding it directly in the session might break something else. These are basic precautions for whenever you cross language boundaries, rather than "hacky code". Just as you escape values before inserting them in MySQL code, you need to escape values before inserting them in JavaScript code. – rid Aug 11 '12 at 21:51
  • I think it's important to note that now that we're using json_encode we cannot wrap the JS var in quotes (it doesn't work otherwise) :o – khaverim Aug 12 '12 at 14:43
  • @khanahk, Makita did say that. The second example does not use quotes. – rid Aug 13 '12 at 01:30
  • Doesn't seem to work. Firebug shows "var sessName = null;" when I use this snippet. – orfdorf Jul 14 '15 at 05:07
  • @SchizoidSpag There is really nothing to this snippet, it's very simple. I guess the value you are attempting to assign is null. Try assigning a string like "hello world". – Makita Jul 17 '15 at 02:51
  • @Makita It turned out to be a php.ini issue causing variables not to persist. Thanks for the snippet! – orfdorf Jul 17 '15 at 02:53
2

You need to use $.post to retrieve the variable from the server. You would have something like this:

 $.post('echoMyVar.php', {post: 1}, function(data){
      myVar = data['myVar'];
      });

This is very basic, you first need to check if data is not null. In echoMyVar.php, you need just need basically the following:

 header('Content: application/json', 1);

 $returnVal = array('myVar', $_SESSION['myVar']);

 echo json_encode($returnVal);

Again this is a shell, not secure, and would not handle any errors.

Greg Rozmarynowycz
  • 2,037
  • 17
  • 20
2
var name= "<?php echo $_SESSION['user_name'];?>"

will do it . . .

Remember php is a server side script, . . .so it takes precedence and get executed first and spits html to the client (Jquery , javacript) which will be executed in your browser . . . .

So, you can use server side variables to share with client . . . but not the other way around . . .

palerdot
  • 7,416
  • 5
  • 41
  • 47
  • As noted for the other answers. You *need* to use [`json_encode()`](http://php.net/json_encode) for this. – rid Aug 11 '12 at 04:29
0

The easiest way is probably to include your javascript code in a .php file. Then you can simply do:

var phpVar = <?php echo $_SESSION['name']; ?>

SIMILAR POST

Community
  • 1
  • 1
Alex Kalicki
  • 1,533
  • 9
  • 20
  • Is there any need when you're just getting a string? – Alex Kalicki Aug 11 '12 at 04:17
  • Of course. There wouldn't be an immediately obvious need if you were absolutely certain that it was an integer. Even then, JSON encoding it would be much safer than simply throwing the contents of the PHP variable into a JavaScript construct. – rid Aug 11 '12 at 04:18
0

Server side in whos_typing.php:

<?php
//...
header('Content-Type: application/json');
echo json_encode(array(
    'who'=>'Bob',
    'session'=>$_SESSION,
    // Be sure that you're not storing any sensitive data in $_SESSION.
    // Better is to create an array with the data you need on client side:
    // 'session'=>array('user_id'=>$_SESSION['user_id'], /*etc.*/),
));
exit(0);

Client side:

// the 'who is typing' shindig
$.ajax({
    url: "whos_typing.php",
    dataType: 'json',
    cache: false,
    success: function(data) {
        var session = data.session,
            who = data.who;
            console.log(session.user_id); // deal with session
        $("#soandso").html(who); //Insert who's typing into the #soandso
    }
});
Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
-1

You need to echo the session variable from PHP when you send it to the browser. I'm assuming whos_typing.html is just the URL to a PHP script.

Jordan
  • 4,510
  • 7
  • 34
  • 42
  • what? what good will echo $_SESSION['name']; do outside of my – khaverim Aug 11 '12 at 04:07
  • It looks like the function of whos_typing.html is to get updated information about something the server knows about. The purpose of ajax is to get that information from the server **after** the browser has downloaded the file containing JavaScript. – Jordan Aug 11 '12 at 04:10