i have JavaScript files that are included at the top of the page and their content is generated by the php script.
we can echo the php variables easily in the .php extension files but what will be the best solution for .js files?
Either convert the data to json and store that in the file and pass to the script or any other better and efficient approach available?
Use Smarty Template engine. You can access PHP variables in JS file like following:
// Code goes here
PHP file:
<?php
$smarty->assign("Name", "PHP");
?>
HTML file or JS file
<script>
var php_var = {/literal}{$Name}{literal};
</script>
Related
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.
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.
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.
<?php
header("Content-type: text/javascript");
include("header.php");
?>
<head>
<script type="text/javascript" src="header.php"></script>
</head>
I'm trying to include a PHP (header & footer) file in an HTML file.
The reason it needs to be HTML is this is a content provider that hosts the content and they've put a restriction on the number of characters that can be in the header (as they host it). Any ideas?
You can not include php in a html page, as php generates html but html can not generate php. So you can try ajax method to include php instead on page load try calling a javascript function which will call the php file.
window.location.assign("header.php");
by this method you can add php file but only in php page..not with html.
In my CakePHP application I am creating a session variable in some controller, which I need to access in a ".js" file. Is there any possible way to do this?
I would suggest passing them as parameters like this -
<a onclick="some_function('<?php echo $_SESSION['var'] ?>')">Click</a>
and have the javascript function some_function() process it instead of assigning them inline. This way you can have the javascript file free from server side code. This is the cleanest way.
I too feel that because session variables are server side, they should not be handled directly in client side language through inline code.
You need to dynamically generate your JS file so that it contains the value you want. You can set up your server to parse .js files through PHP, or you can just name the JS file .php:
var myVar = '<?php echo addslashes($_SESSION['myVar']); ?>';