How can I get my session data using javascript.
First I open my php file (www.sample.com/index.php)
index.php
<? $_SESSION['user'] = "carlo34";?>
<script>var data = '<?php json_encode($_SESSION['user']) ?>';</script>
Then I open my widget (windows 7 gadget)
Then I have a function
test.js
$.get('index.php', function(data)){
alert(data);
});
but it doesn’t alert any.
/////
Thanks thats a helpful tip, but on my case still didn’t work. I just stated some details, sorry about that. I am displaying my session variable on the Client side, I have a script that would load another script on the domain
my.js(client side)
here it will load my script
var url = "http://www.sampledomain.com/test.js";
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
test.js(domain side)
$.get('index.php',function(data)){
alert(data);
}
You’re doing it wrong. First of all, don’t echo PHP data directly into javascript. It’s far too easy to produce a JS syntax error and kill the rest of your Javascript code.
using json_encode guarantees you get syntactically correct javascript, regardless of what’s stored in that variable.
Beyond that, once you’ve done this echo, you don’t need to do any AJAX calls, the value is now JS code as far as the browser is concerned, and you just do:
For an actual AJAX response, in the way you want to treat it, you don’t output any
<script>tags and the like. For a simple “make a request and get a string back”, you’d have your PHP script do:and on the JS side:
would pop up an alert box with “this is some data” in it. If you output
<script>tags and then do the same alert, you’ll get<script>this is some data</script>in the alert, etc…