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 lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
How to use php variable in external js file

Last accessed pages

  1. PHP Simple HTML DOM Parser (12452)
  2. Disable button and Enable it after specified time (17532)
  3. Get Mime Type of file or string content in PHP (6229)
  4. PHP MySQL - using MySQLi (9669)
  5. Integer and Float value in Select with PDO from string to numeric (8658)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (477)
  2. CSS cursor property - Custom Cursors (81)
  3. The Mastery of Love (71)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (63)
  5. CSS3 2D transforms (46)