Defining a variable in js file from php file

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

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

How can I get $ sid in js file to use?

+3
source share
3 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 is somewhat dependent on what is inside javascript.js. If you use the declared variable myFile inside, first declare it. If it's just lib, for example. jQuery, declare it later.

+4
source

Why are you passing the SID simulation? It must be passed through cookies via PHP. Any other variable can be passed through sessions.

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

.

+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 that you load AFTER this.

+1
source

Source: https://habr.com/ru/post/1725825/


All Articles