Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a variable in a js file, from a php file

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?

like image 290
mrpatg Avatar asked Feb 11 '26 08:02

mrpatg


2 Answers

<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.

like image 53
Gordon Avatar answered Feb 13 '26 08:02

Gordon


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.

like image 26
MiB Avatar answered Feb 13 '26 10:02

MiB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!