Skip to content Skip to sidebar Skip to footer

Access Php Variable Into External Javascript File

I get var value into php code. I want to access it into included test.js file.

Solution 1:

Pass it as a parameter:

<input type="submit" onclick="func('<?php echo $var; ?>');">

in test.js:

function func(param){
   console.log(param); // contents of $var
}

Or set it globally:

<script>
   var param = "<?php echo $var; ?>";
</script>

Solution 2:

You can use like this-

<?php
 session_start();
 $var=$_SESSION['my_id']; 
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  var my_id_j = '<?php echo $var; ?>';
</script>
<script type="text/javascript" src="test.js"></script>
<!-- AddThis Smart Layers END -->
</head>
<input type="submit" onclick="func();">  Button </input> //This function call test.js
<body>

Here I have added following line before including the test.js.

<script type="text/javascript">
  var my_id_j = '<?php echo $var; ?>';
</script>

In this the variable my_id_j is global variable, will be accessible in test.js


Solution 3:

There are two ways of handling this scenario:

Usual Case: Passing it as an argument in functions

Example:

 <?php $myvar = 'Hello'; ?>
   // other code
 <script type="text/javascript" src="yourfile.js"></script>

   // and when you are about to call the function:
 <input type="submit" onclick="func('<?php print $myvar; ?>');">

Rather Special Case: Loading the JS file and replacing a special value.

In the past, there have been cases that I couldn't do the above. I can't recall of any easy example at the moment, but what I have done was this:

 <?php
   $my_var = 'Hello';
   $my_script = file_get_contents('path/to/file.js');
   $my_script = str_replace('%SPECIAL_VALUE%', $my_var, $my_script);

   print '<script type="text/javascript">'.$my_script.'</script>';
 ?>

And then I was able to simplify my Javascript by doind anything like:

 var myvar = '%SPECIAL_VALUE%';

 alert('%SPECIAL_VALUE%');

Solution 4:

You will have to pass the variable to javascript first:

<script type="text/javascript">
    var variable = "<?=$_SESSION['my_id'];?>";
</script>
<script type="text/javascript" src="test.js"></script>

You can then use it within test.js either as variable or window.variable.


Solution 5:

You could do this:

<?php
session_start();
$var=$_SESSION['my_id'];  // I want to access $var into test.js included below
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript>
var myJsVar = "<?php echo $var;?>";
</script>
<script type="text/javascript" src="test.js"></script>
<!-- AddThis Smart Layers END -->
</head>
<input type="submit" onclick="func();">  Button </input> //This function call test.js
<body>

Now you can access the var throught myJsVar


Post a Comment for "Access Php Variable Into External Javascript File"