Javascript Course

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 $_REQUEST
if(isset($_REQUEST["id"])) {
  echo $_REQUEST["id"];
}
How to use php variable in external js file

Last accessed pages

  1. jQuery Ajax - load() method (10777)
  2. PHP getElementById and getElementsByTagName (49143)
  3. Multiple Select Dropdown List with AJAX (19875)
  4. JQZoom Image Magnifier (12967)
  5. Highlight Images on click (6659)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (253)
  2. Read Excel file data in PHP - PhpExcelReader (91)
  3. The Four Agreements (77)
  4. PHP Unzipper - Extract Zip, Rar Archives (76)
  5. The Mastery of Love (66)