Usually you can't add php code in external javascript (js) file. But, you can add and use php code in the page in which the external javascript file is included.
So, you can apply the following technique to use value of php variable in js file.
1. In the page in which the external javascript file is included, output the value of the php variable to a javascript variable:
<?php
//php code..
$some_var ='value';
?>
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Page Title</title>
<script>
var js_var ='<?php echo $some_var; ?>';
</script>
</head>
<body>
Page content..
<script src='external_file.js'></script>
</body>
</html>
Now, in the script from external_file.js we can use the js_var
(it contains the value of the php $some_var).
2. For example, in external_file.js:
alert(js_var); // value
The javascript variable must be defined before the external js file is included.
Daily Test with Code Example
HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add definition lists into a <dl> element?
<dt> <dd> <li><dl>
<dt>HTML</dt>
<dd> - Hyper Text Markup Language</dd>
<dd> - Language for web pages</dd>
</dl>
Which CSS property can hide an element on page, letting an empty space in its place?
display position visibility#id {
visibility: hidden;
}
Click on the event which is triggered when the mouse clicks on an object.
onclick onmouseover onfocus document.getElementById("id").onclick = function(){
alert("http://CoursesWeb.net/");
}
Indicate the PHP variable that contains the contents of both $_GET, $_POST, and $_COOKIE arrays.
$_SESSION $_GET $_REQUESTif(isset($_REQUEST["id"])) {
echo $_REQUEST["id"];
}