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.
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.
while(x<=num_of_cpkgs){
var cpkg_navtray = '\'navtrays/' + cpkg_array[x] + '.html\'';
<?php include ?> cpkg_navtray <?php ; ?>;
x++;
}
cpkg_array contains potentially multiple file names. I'm wondering if there's a way to include a Javascript-generated filename in a PHP include statement like this?
This doesn't work like this.
TL;DR:
You need AJAX calls for this.
Longer:
When you load a page in your Browser, the server send you the file. If the file is a php file, then it calls the php to process the file. After the file is processed the server send it to you as a static file.
With JS you can do some interaction to the website. Until now you probably got used to sending each file as a GET or POST data with a form. With JS you have to make an XMLHttpRequest to create a dynamic request and your page is won't be refreshed again however you will get the response as a variable in JS.
Read all about this here.
I'm busy doing server side and client side validation for magento. this validation works fine on server side (php)
on the client side i am using javasrcript.
When i started on this. i had my javascript embedded on a phtml file and everything was working as expected.
because i am using magento so I decided to inject the javascript file via page.xml
When I added the javascript code instead of getting the message pulled I get the php as is.
Here is my javascript:
function DefaultAddressErrorChangeNotAllowedMessage() {
alert("<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>");
return;
}
I run this when a user hit the onclick it will point to this function DefaultAddressErrorChangeNotAllowedMessage()
and the
<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>
will be populated as is.
but when I embed this directly to a phtml file it pull the correct message.
I there a way for javasrcipt that I can use to escape the php and get the correct message which is pulled from config.xml
PHP is rendered server side only. If you need to "inject" PHP specific values to your javascript, then you either need to render the actual value as part of the output of the php script, or you need to take a new roundtrip to the server, using Ajax.
Javascript is clientside, PHP is server side, so all php has been evaluated when javascript is loaded. This means, you can alert php echos, but you can't run PHP operations or any PHP logic in Javascript. You need ajax for this.
sorry for my clumsy answer, but maybe you lost the simple things.
I see that your javascript contains php tag, so i think you should insert your javascript code into .php extension because .js extension can't recognise the php tag.
I'm just learning php, and I am trying to parse some files I have, and then send the information to javascript. This is my php:
$datesArray = readFile();
echo json_encode($datesArray);
This echoes:
["120102000000","120102000500","120102001000","120102001500","120102002000","120102002500","120102003000"]
Which is what I want. However, my javascript, which looks like this:
var dates = <?php echo json_encode($datesArray); ?>;
console.log(dates);
keeps giving dates back as null, and I am not sure why. I have tried encoding the array as utf-8, and I have tried using jQuery.parseJSON which also did not work.
Thanks--
Just checking, but is that JavaScript with PHP in a .js file? By default, Apache only runs PHP in files ending in .php so that would mean your PHP is getting parsed as plain text by the server.
If that is the case, the easiest solution is to run that part of the script in some <script> tags.
Alternatively you could make Apache try to serve .js files as PHP file via Mime-Types; but that is really a mess not worth implementing.