Include PHP variables directly into js files - javascript

I would like to use js code, which works with php variables.
My situation now:
mainFile.php
<?
$myPHPvar = 1234;
?>
<html>
<body>
MY CONTENT
<script>
var myJSvar = <? echo $myPHPvar; ?>
</script>
<script src="myFile.js"></script>
</body>
</html>
myFile.js
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
console.log(myJSvar);
This works ! But I would like to change this structure. I would like to move the myJSvar definition out from main file into the jsFile.
But If I move this line var myJSvar = <? echo $myPHPvar; ?> into the myFile.js it will not work, because this is not an php file.
Not I thought that this could be a solution:
I rename the myFile.js to myFile.php and change the code like this:
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
<script>
var myJSvar = <? echo $myPHPvar; ?>
console.log(myJSvar);
</script>
and in the mainFile.php I changed <script src="myFile.js"></script> to include('myFile.php');
This works !
BUT:
First question of all: Is this a good idea to do it like this?
Second: The "problem" now: All my files are now php files, also the files, which includes mainly js code. That's not very beautiful, because now I can't see on the first view, which is an js file and which is a php file.
Thank you for your support !

Using PHP, echo the values to hidden HTML fields on the page.
When you know the page is done loading, read them back out using JavaScript.
Note, Ideally, you'd just make the data a separate AJAX/xhr/fetch call to a URL (JSON or XML formatted data is nice for this), but as a stop-gap, hidden fields will do the trick for basic PHP pages.
Similarly, you can echo some inline JavaScript (tags and all) and reference the variables elsewhere. This approach will work but is often referred to as "spaghetti code" because the intertwined front-end (JavaScript) and back-end (PHP) code makes for tricky debugging and does not scale well to larger code projects... months or years after, developers will find themselves scratching their heads as to where code lives, how it's generated, where new code should be placed, etc.

You can do it like this. And there's nothing really wrong with it. You have to bring the data to the client browser somehow. You can do this with: 1. set php variables in the DOM 2. XHR call or 3. cookies

This can be achieved by generating the JS file dynamically... You can create a PHP file that would generate the JS dynamically like:
Note: THIS METHOD IS HIGHLY NOT RECOMMENDED. THIS IS FOR YOUR INFORMATION AND KNOWLEDGE ONLY.
myFile.php (The JS equivalent file)
console.log(123)
Your HTML file
<script type="text/javascript" src="a.php"></script>
But this is highly not recommended because JS files are static resources that can be cached. Using this method would request the JS file every time the page loads (where it will only be transferred at first load only if its static).
The best method is to keep the dynamic variables in your HTML and then include your static JS files which will use these variables.

Related

How to include in .php a .html with links to a .js that has php codes

I have a folder that basically contains:
.php
.html
.js
.css
Inside php i need to load .html to display the webpage of course. inside the html there is a script tag that refers to the .js file.
Now inside the JS file i have a php code that is needed to run there. But using my methods of loading the html the .js throws an error
PHP
<?php
$value = 1;
//$html = file_get_html('index.html')
//include ("index.html")
readfile('index.html');
?>
HTML
<html>
<head>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
Javascript
var myNum = <?php echo json_encode($value); ?>;
Unfortunately the way i have included the html thows an error in the .js file
Uncaught SyntaxError: Unexpected token '<'
What am i doing wrong? Are there any other way to include so that i will be able to write php code in my .js file. Unfortunatly im not allowed to change the file extention there can only be one php file. I separated the javascript and css file to make the code a bit cleaner
EDIT:
A lot may seem to be misunderstanding, This is still hapening in the server, basically what i want is that the webpage recieved by the user already has the value for MyNum. I am initializing the variable before it even gets to the user
In your PHP file, create a global variable containing your JSON in a tag:
<script>var myNum = <?php echo json_encode($value); ?>;</script>
and then reference that variable in your script file with myNum.
PHP code runs on the server, the client (the browser in this case) will get only the output of the PHP. In fact, browsers can't execute PHP code.
JavaScript runs in the client. The browser gets the JavaScript code, and executes it.
The only thing you can do if you really want to produce JS code from PHP is to give a .php ending for the js file (test.js -> test.js.php).
With this, the file will interpreted as PHP. The browser gets the result (javascript, that contains the encoded JSON), and everything works well.
If you want to pass $value from the first PHP to test.js.php, read about GET variables.

Load all <script> tags from a different page

I'm hooking into a separate page (same domain) and pulling it into the current page using $.load, which would be fine, if I was doing it for the whole page, but I'm not, I'm just doing it for the JavaScript code in that page. I was wondering if it's possible to load all the script tags from said page into the current page?
I'm currently using the below code:
var newMessageURL = $('#lnkCompose a').attr('href');
$('#hiddenScriptLoad').load(newMessageURL);
Is said page on the same domain or do you have access to it? You will run into trouble with the cross domain origin policy otherwise.
If you do have access, the only way is to parse the html using a regex statement or html parser and pull the scripts manually.
This sounds like a very hacky approach though and I'm not really sure why you'd want to do this.
If you have access, get the page contents and then use the below to get the script tag sources.
text.match( /<script src="scripts\/(.*?)\.scripts\.js"><\/script>/g )
Credit Javascript regex to get src url between script tag
var newMessageURL = $('#lnkCompose a').attr('href');
$('#hiddenScriptLoad').load(newMessageURL);
The above code will load all the contents you have in the second file and it will also import any javascript codes you have there. But the codes you'll have in second file will not work and wont get into action unless you call to them from first page using a function call or in any other manner.
If you just want to separate your js codings and html and have them in two separate files, it would be better to use PHP to import the second file into the first one and in this way, when the page is loaded in the client browser, it will render it as it was just a single file containing both contents. Ex..
<?php
include("script_file.js");
?>
And also if you want get only the js part of the second file use something like this
<?php
$Vdata = file_get_contents('path/to/YOUR/FILE.php');
preg_match_all("'<script(.*?)</script>'si", $Vdata, $match);
foreach($match[1] as $val)
{
echo $val;
}
?>

"Unexpected token <" when using <?php in a Javascript file

Being new to this, I'm trying to pass a variable from PHP to Javascript.
In my php page, I use a test variable:
$testval = "x";
In my .js file:
var exarr = <?php echo json_encode($testval); ?>;
I've tried several things, but it seems I always get Unexpected token < when I include "
What am I doing wrong ?
Thanks !
In order to use PHP code in any file, the web server has to run that file through the PHP processor. This is configured to happen by default with .php files, but not with .js files.
You could configure your server to process .js files as PHP, but that's generally unwise. At the very least, it creates a lot of unnecessary overhead for those files since most of them won't (or shouldn't) have PHP code.
Without knowing more about the structure of what you're trying to accomplish, it's difficult to advise a "best" approach. Options include (but may not be limited to):
Defining that one var on a PHP page which references the JS file, thereby making it available to the JavaScript code.
Putting the value in a page element somewhere that it can be accessed by JavaScript code, either as a form value or perhaps a data value.
Making an AJAX request to the server to get that value (and other values) after the page has been loaded.
If you have that in a js file (like somefile.js) then PHP isn't going to parse that file by default. In the PHP file that links to that JS you can output a script tag and the var you want like:
echo "<script>var exarr = " . json_encode($testval) . "; </script>";
And make sure your script is linked in after that code;
.js files are not compiled by PHP. The easiest workaround is to put the Javascript in a <script> block within a .php, but you're making one of the most basic of serverside/clientside mistakes and should rethink your entire approach.

Access file from project directory and modify it using Javascript

I have a .json file in the same directory as my html file. I want to access this file and modify it. This modified file data will be used to load the contents of the same html file.
How can I access the file and modify it in Javascript?
Being a newbie in Javascript, any help is appreciated.
Thanks.
HTML5 added a file api for interacting with files on your computer.
This HTML5Rocks article explains how to use it.
this MDN page also explains it
html
<input type="file" id="input" multiple onchange="handleFiles(this.files)">
js
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var fileList = this.files; /* now you can work with the file list */
}
api link:
FileReader.readAsText()
You cannot do this solely with HTML and javascript. What you want to do requires reading the file on the web server, not from the user's hard drive. Therefore, you must use a back-end language, like PHP. It's actually pretty easy.
If you haven't used PHP before, you can test that you have access to it (almost everyone does except those on Microsoft OS web servers). Just create a new file called test.php and make it look like this:
<?php
echo 'Hello there';
Then, navigate to http://whatever_your_domain_is/test.php
To access your JSON document, you can either do it as the page is loading, as follows:
(1) Rename the page from .html to .php -- all this does is allow PHP to be processed on the page. Otherwise, it is exactly the same as an HTML page.
(2) Add a section like this at the top:
<?php
$filePath = "json_file_name.txt";
$handle = fopen($filePath, "r");
$json = fread($handle, filesize($filePath));
?>
(3) Later, in your javascript code, plop that into a variable, like this:
$(function(){
var imported = "<?php echo $json; ?>";
var json = $.parseJSON(imported); //or, JSON.parse(imported);
}); //END document.ready
Or, you can use AJAX to do it on demand (i.e., triggered by a user event, such as a button click).
Here are some examples that demonstrate how easy AJAX is.
Note that using AJAX will not allow you to avoid the back-end server language (PHP). AJAX code communicates with a back-end (PHP) file, which does the same work as that described in the above section, and sends the result back to the AJAX success function in the javascript. The advantage of AJAX is being able to do it on demand, instead of just when the page is initially rendered.
Other refs:
how to parse json data with jquery / javascript?

JavaScript with json call working in head but not if in separate .js file [duplicate]

I am just wondering if it's possible to use external JS file that contains PHP code.
my external JS
$(document).ready(function(){
$('#update').click(function(){
var tableVal={};
// a bit of php code I need in JS
var search_city=<?php echo $_SESSION['search_city'];?>';
$.post('<?=base_url()?>/project_detail/pub', {'tableVal':tableVal},function(message)
})
})
})
my view page
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
The JS doesn't work as I assume that the PHP code in JS is the problem. Any thoughts? Thanks a lot.
You can do it by either renaming you js file to php and using this link in script tag src (as pointed in other answers)
While this may seems a good and easy way there is many reason not to do this.
Caching (your generated script will not be cached, this may be changed but require additional work)
Memory consumption (every request to this generated js file will require php)
You can simply changed to something like this to get it done (in a better way, IMO):
<script type="text/javascript">
var Settings = {
base_url: '<?= base_url() ?>',
search_city: '<?= $_SESSION['search_city'] ?>'
}
</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
Than content of your js became something like this:
$(document).ready(function(){
// I assume that not using search_city in your sample code
// and some syntax errors, is just by mistake...
$('#update').click(function(){
var tableVal={search_city:Settings.search_city};
$.post(Settings.base_url+'/project_detail/pub',
{'tableVal':tableVal},
function(message){
console.log(message);
})
})
})
quite a common thing to want to do, just rename your js file to "external.js.php" (i use that method, but as long as it ends in php it doesn't matter what you use really) then just change the src url in your script tags and away you go.
Dont forget you may need to include function and config files into the javascript for that base_url() function to work.
Unless you need php for a lot of things in your js file, I'd suggest you don't do as mentioned above and not rename your js file to php to have it parsed. JS files are best served as static.
One thing you can do is have a script at the top of your php document where you assign your base_url variable as a global to be used by all your js:
In your page, before including any js
<script type="text/javascript">var base_url = "<?= base_url();?>";</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>
In your js file
$(document).ready(function(){
$('#update').click(function(){
var tableVal={};
// a bit of php code I need in JS
var search_city=<?php echo $_SESSION['search_city'];?>';
$.post(base_url+'/project_detail/pub', {'tableVal':tableVal},function(message)
})
})
})
I believe it is possible, but as Brian mentioned you have to let the preprocessor know it needs to process it. You can either tell it to use php to handle .js files (Not recommended) or simply use a .php file for your javascript, then use:
<script type="text/javascript" src="<?= base_url();?>js/external.php"></script>
This should be okay because the mime type is still javascript so it will be interpreted that way. I've never actually tried this, so it is a guess, but I believe it should work.
Just a quick idea, that could help some people:
I think (never tried) there is also a way to ask the web server (Apache, etc) to let JS files be handled as PHP content.
Advantages:
No need to rename your JS files to .js.php
Takes advantage of caching
Can be applied only to a specific folder (not to every JS file of your website)
Withdraws:
Do not forget that those "php" files are "cached" somewhere, so don't rely on the fact that files are generated every time.
Server resources: as said in other answers, make sure to use such a trick only when it's really not possible to put PHP code outside of the JS files (using ajax queries for instance), or on files that don't load the server too much.

Categories

Resources