Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

<html><head><scriptsrc="javascript.js"type="text/javascript"></script><scripttype="text/javascript">var myFile = 'myfile.php?sid=' + "<?phpecho 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.

Solution 2:

<?$sid = session_id();
?><html><head><scripttype="text/javascript">var sid = '<?=$sid?>';
</script><scriptsrc="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.

Post a Comment for "Defining A Variable In A Js File, From A Php File"