1

i have a php file in which i am calling external takeatour.js file in that js file i want php session data.by using a code....

$(this).ready(function() {

    var category = <?php echo json_encode($this->session->userdata('category')); ?>;     
   alert("category="+category);
});

is it correct?? plz give me some suggestion. Thanks!!

7
  • Please post your full code!! Commented May 28, 2015 at 8:22
  • 1
    possible duplicate of How to pass variables and data from PHP to JavaScript? Commented May 28, 2015 at 8:23
  • If you are using Static method, Then why CI?? CI have library call SESSION Commented May 28, 2015 at 8:24
  • 1
    PHP (server) --> HTML --> Javascript (client). You can only echo the value so it'll be present in the HTML to be available from javascript. Client doesn't have direct access to PHP variable, but you can ask the server (ajax for example) for the value. Commented May 28, 2015 at 8:24
  • The file should be with .php extension. .js will not execute php. Commented May 28, 2015 at 8:27

3 Answers 3

2

You can pass the session variable from PHP code to javascript code like this:

<?php
$variablephp = $_SESSION['category'];
?>

<script>
var variablejs = "<?php echo $variablephp; ?>" ;
alert("category = " + variablejs);
</script>

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

Comments

0

Add .php to the end of the javascript file. That way the server will process it.

If you include it in a page that a client will download later, make sure to type=text/javascript" in your script tag because it won't be happy with the extension otherwise.

Whatever editor you use will likely not syntax highlight properly since you will not be following php conventions.

Comments

-1

you can pass the category value as a parameter in the src attribute. For example:

<script src="myjs.js?category=<?php echo $this->session->userdata('category'); ?>"></script>

and then get the category value inside your script.

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.