Leon Armstrong
Leon Armstrong

Reputation: 1303

session variable cannot be access inside a dynamic javascript file

I know the my question is weird , but it is my situation. I am calling a javascript with

<script src="js/jscript.php"></script>

And in the other hand i am writing javascript inside jscript.php

<?php 
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Content-Type: text/javascript");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
?>$(document).ready(function(){
....
....
....
alert('hello world!');//all my javascript stuff

<?php
echo $_SESSION['user_id'];  //echo nothing
echo $_SESSION['user_email']; //echo nothing
?>

});

And then i tested with my browser , file calling and those call like alert('hello world!') have no problem but until i try to access session variable from jscript.php , its all empty ... I did set those variable correctly

Upvotes: 0

Views: 378

Answers (2)

Leon Armstrong
Leon Armstrong

Reputation: 1303

Adding a session start a very start of jscript.php solved my problem

session_start();

hope its help others.

Upvotes: 0

Morsok
Morsok

Reputation: 126

I'm not sure that can work.

I think a better way would be making an ajax call to a PHP page, getting back the data in whatever form you want (json, or just echo $var ...) and then do something with it.

ex with jquery:

<script>
    $.ajax({
        url: 'mypage.php',
    }).done(function(msg) {
          // Do something with msg here
    });
</script>

and mypage.php could be like :

<?php

$response = array();
$response['user_id'] = $_SESSION['user_id'];
$response['user_email'] = $_SESSION['user_email'];
echo json_encode($response);

?>

When the ajax call is made, the php page will create an array, fill it with the session variables you need and return it to your script in a json form with json_encode. You get it as a var in .done method and do whatever you need with it.

Upvotes: 1

Related Questions