Well, as others said, you cannot mix JS with PHP. This is Client/Server architecture where both are separated.
I don't know about your case, but if you are printing JS from php (means from the same .php page) then your approach might work depending on what you need.
But since your JS is on a separate files. Then it will be executed only when it's loaded by the client's browser.(is this what you want?)
Once the code is on the client browser, it cannot see what's on the server. The only way to get some data from the server is by initiating a request to pull the data thru AJAX request (i suppose there are other ways, but i'm limiting my self to your case).
Therefore we have two cases.
Case 1 : Seperate JS from PHP and put it in a separate file.
Example script.php
<?php
$filename = "./about.txt";
$doc = file_get_contents($filename);
echo $doc;
?>
.
.
action.js
//using pure js ajax request
function get_about() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Connection lost. Please try again.");
return false;
}
}
}
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
document.getElementById("div2").innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "script.php");
ajaxRequest.send(null);
}
Case 2 : Both JS and PHP are located on the same file, mean JS will be printing along with PHP code and sent all together to the client's browser.
Method 1: open javascript tag and put ur js code there
Example script.php
<?php
$filename = "./about.txt";
$doc = file_get_contents($filename);
echo "<script>
function get_about() {
document.getElementById("div2").innerHTML = '{$doc}'
}
</script>";
?>
Note that putting $doc into a js string might break down if it contains (",',>,<,\,/)depending on your html.
Method 2: combination of the previous approaches. Assign data to JS varibale and access it from JS file. In this way you can still have your separate JS file
Example script.php
<?php
$filename = "./about.txt";
$doc = file_get_contents($filename);
echo "<script>
var doc = '{$doc}'//global variable
</script>";
?>
action.js
//using pure js ajax request
function get_about() {
document.getElementById("div2").innerHTML = doc ;
}