Inserting php into js file - php

I have a loading gif for the gallery on my website. In my js file I have this code to show the loader:
image: $("<img src='images/loading.gif'/>"),
Currently this the image isn't appearing because I haven't put the full image path. But instead of putting the full image path, I would prefer to do this:
<img src="<?php bloginfo('url');?>/images/loading.gif”>
But I can't work out how to make this php work in my js file. How do I go about doing it in the easiest way?

I prefer to..
1) In my header include (the php include that contains any <head> data), write a small
inline JS function that creates a global object containing any variables I need from the server (PHP). I can use the 'echo' and 'json_encode' functions here because its in an inline JS snippet in a php file.
2) You could write a JS function inside your JS file that uses AJAX to call a PHP file, which will return the same JSON encoded data as number 1, then you parse it and assign in to a global variable.
Both essentially do the same thing, except with 2 you are using AJAX, which will add an additional request. I prefer option 1, because it is done along with the pages execution. Option 2 may require you to wait until the DOM is ready, depending on various aspects of your program (in which I can not tell).
Option 1 requires inline JS, but you really shouldn't harp on this, as with dynamic websites it can actually be a plus, as along as it is short and concise. Some people get on others about inline JS. Don't let them yell at you.

I am not totally sure what you are trying to do. But if that JS isn't working, why not including a php file, or just writing some php in the header, that includes the JS inside it in 'echo()'. I.e:
echo('?><img src="<?php bloginfo('url');?>/images/loading.gif" /><?php');
Correct me if I am misunderstanding your intent.

You can't place PHP code directly into a .js file, but you could have some javascript in the head element of your PHP file right before including the javascript file.
In this javascript you could then define variables and assign data to them using PHP. These variables would then be accessible from inside the javascript file.
<head>
<script type='text/javascript'>
var _g_bloginfo = "<?php echo '...'; ?>";
</script>
<script type='text/javascript' src='javascript.js'></script>
</head>

A cleaner technique for passing PHP data to JavaScript is to store the data in data attributes which you can then access via JavaScript. As a simple example:
<body data-home-url="<?php echo home_url(); ?>">
You can access that in jQuery like:
var home = $('body').attr('data-home-url');
FYI you can use json_encode to convert PHP object/arrays into a JSON objects which you can read via $.parseJSON or JSON.parse. WP's wp_localize_script can actually do this for you, but note that in that case it'll expose the converted data to the window.

You can create a php file instead (of your js file with all the code you already have in that js file + references to your php variables/functions) and include that in your main php file.
Example html:
<?php $example = 23; ?>
<html>
<head><title></title>
<script type="text/javascript">
<?php include('js.php'); ?>
</script>
</head>
<body></body>
</html>
js.php:
var a = <?= $example ?>;
alert(a);
will eventually output:
<html>
<head><title></title>
<script type="text/javascript">
var a = 23;
alert(a);
</script>
</head>
<body></body>
</html>

Related

Best place in html page for php block when passing variables to javascript

I have a simple HTML page and I feel unsure about which is the best place to put a PHP block that loads 2 JSON arrays from files so that they can then be passed on to JavaScript variables.
I have placed it here, but I have no criteria:
<!DOCTYPE html>
//i have placed the block here
<?php
$twit_collection=file_get_contents('cdtwbot_twit_collection.json');
$tag_collection=file_get_contents('cdtwbot_tag_collection.json');
?>
<html>
<head>
<script type="text/javascript">
//pass PHP variables declared above to JavaScript variables
var twit_collection = <?php echo $twit_collection; ?>;
var tag_collection = <?php echo $tag_collection; ?>;
</script>
</head>
<body>
//document continues...
</body>
</html>
Would it be better placed inside the <head> tag? Or somewhere else?
There is a great post about passing variables from PHP to JavaScript here but it doesn't cover this point.
From a purely technical standpoint, I'd say it doesn't matter. You can put your php code anywhere on the page, so your solution makes as much sense as putting it anywhere else. There are no convention where to put php code, such convention like you should put your JS code in the <head>, but if you want one I'd say insert it next to the JavaScript variables, because it makes the code more understandable.
In this very example, however I wouldn't use separate variables for this case, as it just confuses the matters, and slows down the code. (Unless, of course, you want to use the variables more than once.)
I'd change the code to this:
<script type="text/javascript">
var twit_collection =
<?php echo file_get_contents('cdtwbot_twit_collection.json'); ?>;
var tag_collection =
<?php echo file_get_contents('cdtwbot_tag_collection.json'); ?>;
</script>
Also, I'd add that this is needless to use php in this case, as JavaScript can parse JSON files much faster than PHP, and it makes much more sense not to mix these two types of code. I'd rather just make these variables in the JSON file ( var twit_collection = ... ) and include it into my html as I can. Look at this article here, the 49 upvoted answer (second answer) pretty much clarifies my point.
Regarding the comment on that answer: I didn't even notice but he used a string and parsed it to the JSON object. It is correct, but JavaScript accepts JSON object natively, such as:
var twit_collection = {array: [{key: value1}, {key: value2}, {key: value3}] };
So to make that answer completely right, just omit the apostrophes before and after the JSON object and ditch that JSON-parsing.
It probably makes sense to pass the variables right before your javascript-file using it. Generally it is seen as best practice in most cases to place JavaScript right above the closing </body> show the user as much of the website as early as possible. Then your html would look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$twit_collection=file_get_contents('cdtwbot_twit_collection.json');
$tag_collection=file_get_contents('cdtwbot_tag_collection.json');
?>
<script type="text/javascript">
//pass PHP variables declared above to JavaScript variables
var twit_collection = <?php echo $twit_collection; ?>;
var tag_collection = <?php echo $tag_collection; ?>;
</script>
<script src="path/to/your/js/file.js"></script>
</body>
</html>
If you need your javascript early, I'd recommend you to put it in your head AFTER your charset declaration (e.g. <meta charset="utf-8">)
It would be a good idea to separate the logic from your view component.
controller.php
<?php
$twit_collection=file_get_contents('cdtwbot_twit_collection.json');
$tag_collection=file_get_contents('cdtwbot_tag_collection.json');
include('view.php');
view.php
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
//pass PHP variables declared above to JavaScript variables
var twit_collection = <?php echo $twit_collection; ?>;
var tag_collection = <?php echo $tag_collection; ?>;
</script>
</head>
<body>
//document continues...
</body>
</html>
As far as where the javascript should go, that depends on whether you need the variables before or after the DOM has loaded.
PHP automatically minifies your javascript and html code therefore echoing the whole page is optimal for user webpage load times but it is also more work on your server. However if your webpage is already minified then your above script would be optimal.

php arrays in external js file

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>

echo php variable on external javascript possible?

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.

Evaluating php generated javascript "inline"?

If you look at the source of this page http://kingston.talking-newspapers.co.uk/ you will see a large amount of inline javascript near the top.
I don't really want all this extra stuff floating around in my page source, I'd much rather get it off into a script tag, and then I can minify it and all sorts.
If I call it as a php file, this SHOULD work in theory, I just end the js file extension with php instead, and in the header I put the following:
header("Content-type:application/x-javascript");
but... a lot of the php variables used to generate the playlist within the javascript are setup at the beginning of the main index.php file, and in calling this php-generated js playlist file like this, it seems to evaluate it entirely separately, so it's full of errors.
The only way round it I can think of is to have the page write a file, then immediately read it in. The other thing is, the playlist is likely to change often and dynamically, so I think I need to get minify to NOT cache it?
I made the solution by following this tutorial, which redirects the generate inline script to a file, then immediately reads that file in.
http://my.opera.com/zomg/blog/2007/10/03/how-to-easily-redirect-php-output-to-a-file
So now my page looks like:
<?php
require("./filewriter.php");
$obfw = new OB_FileWriter('jplay_gen_playlist.js');
$obfw->start();
require($includesdir . "jplayerscript.php");
$obfw->end();
?>
<script type="text/javascript" src="jplay_gen_playlist.js"></script>
et voila! All nicely external, can be minified, cached etc.
You can do it in two ways. First would be set up the variable inline and then include the script:
<script type="text/javascript">
var myPlayList = [
{
name: "Introduction and guidance on usage",
mp3:"http://www.talking-newspapers.co.uk/find/soundfiles/TnHomePageIntro.mp3",
ogg:"http://www.talking-newspapers.co.uk/find/soundfiles/kingstonkt9.ogg"
}
...
</script>
<script type="text/javascript" src="myinclude.js"></script>
The other would be to have your included .js file a simple library of functions which you include at the top of the page and then call from some inline javascript:
<script type="text/javascript" src="myinclude.js"></script>
....
<script type="text/javascript">
$(function() {
var myPlayList = [ ... ];
startPlaylist(myPlayList);
});
</script>
I would personally choose the second method. You shouldn't need to generate any of the script dynamically (as far as I can see, it can all be hard-coded except for the playlist, right?) Any other things you need to pass to the script could still be passed in by your startPlaylist() method call anyway.

Organising code that includes php and javascript files

I have a website where I am including a php library file and a javascript library file. I have condensed the problem to the following files:
index.php
<?php
include('constants.php');
?>
<html>
<head>
<script type="text/javascript" src="lib.js"></script>
</head>
<body onload="javascript:show_const_1('<?php echo(CONST_TEXT); ?>');
show_const_2();">
Some text here
</body>
</html>
constants.php
<?php
define('CONST_TEXT', 'Hello World');
?>
lib.js
function show_const_1(string)
{
alert(string);
}
function show_const_2()
{
alert('<?php echo(CONST_TEXT); ?>');
}
The result is that when the page loads I get two message boxes. The first says "Hello World" and the second says "<?php echo(CONST_TEXT); ?>". The first javascript method does what I want it to, but I will be using the function in many places across the site and so ideally I don't want to have to pass the constant as a parameter every time.
Is there a good way to rearrange the code to make the second javascript method work?
The simple answer is rename "lib.js" to "lib.php".
You should also add
header('Content-type: text/javascript');
to the top of the file.
Incidentally, you should us json_encode() to output text to javascript:
alert(<?php echo json_encode(CONST_TEXT); ?>);
And "javascript:" doesn't belong in event attributes (which are kindof outdated anyway):
<body onload="doSomething();">
The method body inside alert() is not interpreted by PHP (it's interpreted by Javascript), so you can't put PHP tag in it

Categories