3

I have a javascript file that needs a value from a variable in a php script in which the JS file is being called.

<?
$sid = session_id();
?>
<html>
<head>
<script src="javascript.js" type="text/javascript"></script>
...

How can i get $sid into the js file for use?

3 Answers 3

4
<html>
<head>
<script src="javascript.js" type="text/javascript"></script>
<script type="text/javascript">
    var myFile = 'myfile.php?sid=' + "<?php echo session_id() ?>";        
    $('#stuff').fadeOut("fast").load(myFile).fadeIn("fast");
</script>

The order of inclusion somewhat depends on what is inside javascript.js. If you are using the declared 'myFile' variable inside, declare it first. If it's just a lib, e.g. jQuery, declare it afterwards.

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

2 Comments

Changed the order, the variable needs to be before the JS file.
How would i place that var in the script as such; $('#stuff').fadeOut("fast").load('myfile.php?sid=').fadeIn("fast");
1

Why on earth do you pass SID explicity? It should be passed throught cookies by PHP. Any other variable could be passed through sessions.

$('#stuff').fadeOut("fast").load('myfile.php?sid=<?php echo session_id() ?>').fadeIn("fast");

Read more about client/server languages and differences between them.

Comments

1
<?
$sid = session_id();
?>
<html>
<head>
<script type="text/javascript">
var sid = '<?= $sid ?>';
</script>
<script src="javascript.js" type="text/javascript"></script>

Now you can use the sid variable in javascript.js, or any other JS code you load AFTER this.

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.