I have some php variables that need to be used in javascript. Instead of passing vars back and forth using ajax, I chose to parse js files as php. Here's a simple example of what I did:
#.htaccess
AddType application/x-httpd-php .js
//scripts.js
//or for security reason, I could just use scripts.php and add header at the top)
header("Content-type: text/javascript");
alert("Hello <?php echo $_SESSION['username']; ?>");
I'v been using this method for a while, and I haven't noticed any obvious problems.
Are there any side effects doing things this way? Thanks.
I can't see any problem with this, but an easier solution for me was:
<script type="text/javascript">
var username = "<?=$_SESSION["username"]?>";
</script>
in the head-Zone of the template or index.
Related
my question is simple, can I do not have any .js file in my website, just php with header, like this?
Header("content-type: application/x-javascript");
why? to protect my .js files, prevent direct access.
Can I? or it will make my website slower?
thank you!
The only way to have a acceptable result is to parse (compress) the js code, but since there are programs with autoformat this is useless aswell.
But i found i solution that works fine for me,
First use:
<script type="text/javascript" language="JavaScript" src="_js/script.php"></script>
then in you script.php you will be able to make a check for example if a session variable is set then you use you header with the content-type and just echo all the js. Works fine for me.
I have this change request to move all my inline javascript to an external file. I tried a simple copy-paste to a new file, but no luck. I'm getting error at the following line:
var grp_list = <?php echo json_encode($arr_grp); ?>; and
url: "<?php echo $_SERVER['PHP_SELF']; ?>"
I have atleast 20 such occurrences. How do I replace these php variables in external javascript??
I checked lot of forums but did not find any solution.
Thanks a lot for your help!!
Well, you have JavaScript dinamically "assembled" in your PHP script. The easiest solution is to forget about translating the variables. Instead, put all JS code, including the PHP portions, in a PHP file which will pretend to be a JS file, using a custom header. So, your "JavaScript" file will be like this:
<?php
// Send a custom header, so that it will be interpreted as a js file.
header("Content-Type: application/javascript");
?>
JavaScript and PHP mixed code will go in here, with no modifications
Save this file as something like "javascript.php". Then, in your main HTML or PHP file, include it as:
<script src="javascript.php"></script>
That's it! The javascript.php file will be interpreted as a PHP file in the server and retrieved by the browser as JS. Only pay attetion on the kind of processing the PHP in the javascript file does: it may depend on the context you had in the main script, so additional adjustments may be necessary.
In short, you can't pass the PHP variables directly to an external JS file without some work in PHP generating the files, then sending custom headers to treat the file as JavaScript (edit: see post by Marcovecchio if this sounds like a likely solution)... a quick solution is to pass the variables inline so they are global, then use them inside your external file. This will allow for the majority of your JavaScript to be in external files, but also allow you to pass your variables from PHP to JS.
By no means is this the best solution, but it's more than likely the easiest to get working.
Here's an example:
<script type="text/javascript">
var grp_list = <?php echo json_encode($arr_grp); ?>;
var url = "<?php echo $_SERVER['PHP_SELF']; ?>";
</script>
<script type="text/javascript" src="external.js"></script>
I need to be able to insert some PHP into an external .js file. Is this possible? I have created a slider using basic slider and need to have the page titles as markers at the top of the slider.
This is the code the .js file uses to generate the markers currently.
var slidenum = key + 1,
var marker = $('<li>'+ slidenum +'</li>');
I need to replace '+ slidenum +' with the WordPress function 'get_title'. Can this be replaced with php?
You can define JS variables in your php files, then use those variables in your external js.
for example, in one of your PHP files, you can add:
<script type="text/javascript">
// variable1 = number
variable1 = <?php echo $var1; ?>;
// variable2 = string
variable2 = "<?php echo $var2; ?>";
</script>
And for your question:
<script type="text/javascript">
slidenum = "<?php the_title(); ?>";
</script>
the_title() reference: http://codex.wordpress.org/Function_Reference/the_title
Update - The Loop:
<?php
$slider_titles = array();
if ( have_posts() ) : while ( have_posts() ) : the_post();
// your codes go here
$slider_titles[] = get_the_title(); // adds the title to the array
endwhile; endif;
?>
<script type="text/javascript">
slidenum = <?php echo json_encode($slider_titles); ?>;
</script>
When your loop is over then you add the javascript part
Some people are trying to tell you to use Ajax for this. That isn't the solution in this case. The variable is static for the lifetime of the page load, so there's need to keep going back to the server to get the value.
Others are suggesting setting the server to parse JS files as PHP so that you can embed PHP code into them. This also isn't a good answer, because you will lose all the browser's ability to cache the JS file, which will slow down your site and increase your bandwidth costs.
The solution is simply to add a separate single chunk of JS code to your page header -- ie add a small <script> tag to your page template, setting the variable in question.
The variable will then be accessible as a global in any JS code your run elsewhere in the page.
Yes, you can replace slidenum with get_title.
No, you cannot do this with javascript nor at runtime. You'll need to use AJAX for that.
Not directly. You can jump through a few hoops to get it done.
Problem is that .js doesn't get interpreted by PHP at all.
So if you must, you can use mod_rewrite and the like to pretend your php script is actually an .js.
Or write the js file from PHP completely to filesystem.
Or use XHR (Ajax) to fetch a certain value.
Another solution, not the best IMHO, is tell Apache to parse js files as php files. Simply put this in your .htaccess file:
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
I (absolute php beginner) was given a script with different variables that are based on date and time on the top of xhtml strict page:
<?php
$var1="2011,9,31,18,0,0";
[...]
?>
Inside the html body I have a javascript that currently starts like this:
<script type="text"/javascript">
dateFuture = new Date(<?php echo $var1; ?>);
[...]
</script>
Is it possible to make the javascript external, but still pull the variable $var1 from the top of the index page and then have it show the same output on the index page as it currently does?
I have found one example where the beginning of the external .js is supposed to look like this:
dateFuture = new Date(<?php include("/index.html");echo $var1;?>);
Unfortunately that doesn't seem to work.
Is there any possible solution for this?
Any help is greatly appreciated.
Thank you in advance.
Yes. Make the javascript variable global and you can access it inside you external js file.
Something like this
<script type="text/javascript">
var dateFuture = new Date(<?php echo $var1; ?>);
</script>
<script src="your-external-js-file.js" type="text/javascript"></script>
In your-external-js-file.js, you can access the dateFuture.
Or you can encapsulate the code in external js file in a class and pass on the date from php as a parameter to the constructor of that class.
The external JavaScript file itself can point to a PHP file — provided that the PHP file outputs valid JavaScript. That way, you can do something like the following:
myJS.php:
<?php
// Initialize your PHP variable(s) here, or include the PHP script(s) to do so.
$var1="2011,9,31,18,0,0";
...
?>
dateFuture = new Date(<?php echo $var1; ?>);
In your HTML file:
<script type="text/javascript" src="myJS.php"></script>
Since the output of myJS.php is purely JavaScript code, the file extension will not matter to the browser. Same way as your PHP code currently outputs purely HTML code, and your browser understands how to parse that as well.
If your purpose is to move the javascript code to an external script for better modularization, you can move it to a php file and then reference php file as javascript.
<script type="text/javascript" src="myscript.php"></script>
Inside myscript.php -
<?
Header("content-type: text/javascript");
dateFuture = new Date(<?php echo $var1; ?>);
?>
Whilst the answers given by Jonathan Newmuis and RonakG are perfectly acceptable and will work, the purpose of this answer is to answer your question as close to the setup you've got now as possible. However I'd personally agree with RonakG's answer.
If you're using Apache on your server then add the following line to your .htaccess file: AddType application/x-httpd-php .js. Alternatively you could add that code into the Apache configuration if performance is an concern for you.
The goal of that code is, essentially, to say that PHP should parse all files ending in ".js" as if they were ".php"
Yes. It is possible. However, you are going to have to make the javascript file into a php file, or force Apache, or whatever web server you use, to run javascript as php (perfectly harmless, because all code outside of <?php ... ?> is just written to output).
In my-external-js.php or my-external-js.js (whichever you choose, though I would recommend the former, because it requires less configuration):
<?php require_once 'file-which-defines-var1.php'; ?>
dateFuture = new Date("<?php print $var1; ?>");
Note: you should always use require_once instead of include or require, so that the same file is never included twice, which leads to messed-up variables and colliding functions/classes. Also, require and require_once case Fatal errors if the script could not be loaded, while include and include_once do not.
I was wondering wether there is a way to include some html content inside another html using only html?
A replacement to PHP's
<?php include("file.php"); ?>
Is this possible?
EDIT:
This has brought up some confusion, what I needed was "almost an html tag" that had the functionality of including a html document in another.
Have you tried:
<object type="text/html" data="file.html"></object>
It cannot be done purely by HTML. (There are iframes, however, but I don't think that qualifies in this case.)
It can be done using JavaScript. You get the other file via Ajax, and place its contents inside an HTML element on the current page.
Shameless plug of a library that I wrote the solve this.
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
The above will take the contents of /path/to/include.html and replace the div with it.
HTML does not have a feature to include additional content natively. However most web servers do have server-side include statements:
SSI in Apache
SSI in IIS
the only thing would be an iframe which is pure html. but you also can use javascript to get the page via ajax and include it into your dom hirarchy
Yes there is but you need to enable it in your config or .htaccess:
Options +Includes
AddType text/html .shtml
AddHandler server-parsed .shtml
Of course with that youd need to rename any file doing the including to .shtml... or you could jsut use:
Options +Includes
AddType text/html .html
AddHandler server-parsed .html
the syntax itself is similar to comment:
<!--#include virtual="/footer.html" -->
There's no such thing. You'd have to use a server-side scripting language or JavaScript to do something like this.
If you're using Apache, you can try Server Side Includes.
This might be a few years late but this is how i did it !
in the first line after put this line !
<SCRIPT LANGUAGE="JavaScript" src="http://yourdomain.com/header.js">
then create a file called "header.js" and enter the content of the file you want to include !
like so....
<!-- Begin
document.write('<center>');
document.write('a link 1');
document.write('a link 1');
document.write('a link 1');
document.write('a link 1');
document.write('<hr>');
document.write('</center>');
// End -->
Hope this help !
Almost 10 years later, some people may still have doubts about this. So I'm going to explain a simple solution that we have today in 2020.
I always use the jquery .load() function and never had a problem with that.
Exemple: ( "#content" ).load( "includes/menu.html" );
The lack of Include\Import in Html is really frustrating!
A good alternative is "Server Side Includes (SSI)" in case "PHP" is not supported!
SSI is supported by almost any (if not all) web host server!
<!--#include virtual="layout.html" -->
The file that contains the above line must end with ".shtml" or ".shtm" extensions!
It's really annoying that something as easy as Include\Import can't be performed by the browser itself!
Like php or Node.js, preprocessing the html using Javascript itself before the HTML Load process start should be supported in any browser!
Now in 2022 I use Vanilla Javascript fetch().
This is how to include
file: "newfile.html" into
div: "container"
// HTML
<div id="container"></div>
// JS
const loadHtmlFile = (fileName, containerId) => {
fetch(fileName).then(function (response) {
return response.text();
}).then(function (html) {
containerId.innerHTML = html;
}).catch(function (err) {
console.warn('Something went wrong.', err);
});
}
loadHtmlFile("newfile.html", container)