1

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

1
  • PHP tag is not allowed in .js file. You have to use ajax for it. Commented Feb 4, 2016 at 10:40

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

It's not error to use single quotes here. because you're in php and outside quote is just text.
@jcubic, I guessed so but was not sure ;) Inner statement will be parsed first(pre-processed) and will be wrapped by outer quotes, am I right ?
2

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

Comments

1

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);
});

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.