在javascript中访问codeigniter会话变量[关闭]

How to access codeigniter session variables inside javascript? If I create session variable inside plain php and access it in javascript it gives me result but in case of codeigniter session variables it gives me syntax error.

I use following code of line to access codeigniter session variable in my .js file

var m1  = "<?php echo json_encode($this->session->userdata('max_age')); ?>";

"I use following code of line to access codeigniter session variable in my .js file "


You cannot put PHP code inside your .js file. It will not be parsed. You must put your code in the PHP file that your .js file is being called from.

For example:

<script type="text/javascript">
var m1  = <?php echo json_encode($this->session->userdata('max_age')); ?>; 
</script>
<script type="text/javascript" src="script.js"></script>

As I mentioned in the comments above, the problem is most likely caused by an empty php echo output. You stated above that you DO NOT have quotes around your echo statement. So in your code it looks like this:

var m1  = <?php echo json_encode($this->session->userdata('max_age')); ?>; 

This might be a problem if your php variable $this->session->userdata('max_age') is empty. Because if that is the case, json_encode will output an empty string. Please do a "View Source" in your browser and look if that line looks like this:

var m1  = ;

If it does, you found your problem. The above is invalid and would cause the syntax error.