简体   繁体   中英

How to get the php session data in javascript function of a .js file

I want to take the session data in .js file.Here i want the data in a function Now i'm directly put the value.How to take it from session.

.js file

  function callAllfnt(){ 
   get_data(1) ;
  }

I want the 1 as session data.How to take it

If you want it on page load the try this:

function callAllfnt() {
  var data = "<?php echo $_SESSION['givenName']; ?>";
}

In later part in the life cycle of the application, use AJAX

1)

View File

<script type="text/javascript">
var Sessionvalue = "<?php echo $this->session->userdata('session_name')";
<script>

After load your js file

<script src="<?php echo base_url(); ?>js/file.js" type="text/javascript"></script>

JS FILE

function callAllfnt() {
  var data = SessionValue;
}

(OR)

2) Using Ajax call and Get the Session value

You need to create php script that will return Session data and call that with ajax like this:

php

if (isset($_GET['var'])) {
   echo json_encode($_SESSION[$_GET['var']]);
}

js with jQuery:

function get_data(variable, callback) {
    $.get('session.php', {'var':variable}, function(data) {
       callback(data);
    }, 'json');
}

and you can call that function using:

get_data(1, function(value) {
   alert(value);
});

just use php tag with in single quotes if you java script is written in html page like

function callAllfnt() {
    var value = '<?php echo $_SESSION["varName"]; ?>';
    get_data(value) ;
}

But if your javascript code is written seperate js file then use ajax.

Third option is if your javascript file included in php file then create a javascript variable on top of js file including code and use that variable in js file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM