Organising code that includes php and javascript files - php

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

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.

Is there a way to overwrite a page's <title> tag by using PHP within the body?

I'm pretty new to PHP and was wondering if there was a way to overwrite what is displayed in a title tag by using PHP inside the body.
Let me explain why I'm trying to do this. I'm using a forum/cms software that allows me to create PHP pages, but won't let me change anything about the header (including the title tag). I was hoping there was a script that I could place into the body using PHP that would overwrite whatever was displayed into the default title tag.
This is probably a crazy question, and if so I apologize.
Just running out of ideas how to get what I need in the title.
Thanks!
You can't.
if you want to change it add some Java Script code that will execute on the client side and do this for you:
<script>
document.title = "This is the new page title.";
</script>
And with some PHP:
<head><title>some title</title></head>
<body>
<?php if (some condition, etc) { ?>
<script>
document.title = "This is the new page title.";
</script>
<?php } ?>
</body>
<html>
<head>
<title>Hello</title>
</head>
<body>
<?
echo "<script>document.title='Hello, World!';</script>";
?>
</body>
</html>

Inserting php into js file

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>

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.

php getElementById

I have a small problem, I would like a div to be displayed when someone hovers over an image, the problem is that this image is inside php, and there for document.getElementById doesn't work. Is there a way to get round this?
<?php echo "<img onmouseover='xxxxxx' src='img/img.png'>" ?>
what goes in x?
You need to create a javascript function on the webpage where this particular line of code is echoed to the client that will handle the onmouseover event, like this:
<html>
<head>
<script language="javascript" type="text/javascript">
function imageSwap() {
var img = document.getElementById("img1");
//swap out the image...
}
</script>
</head>
<body>
<?php echo "<img id='img1' onmouseover='imageSwap()' src='img/img.png'>" ?>
</body>
</html>
I have a small problem, I would like a div to be displayed when someone hovers over an image
Make sure the information is accessible to people who don't use a pointing device too
the problem is that this image is inside php, and there for document.getElementById doesn't work.
You have misdiagnosed the problem. PHP runs on the server and its output is sent to the client. It cannot prevent something from working (although it can be written badly so it outputs something you don't expect).
If you think PHP is the cause of your problem then you need to stop asking "Why does the JS embedded in this PHP not work?" and start asking "Why is the JS that is outputted from PHP different from the JS I'm trying to write?"
what goes in x?
It is hard to say without seeing the rest of the code.
It depends on why you can't see the div in the first place. Is it invisible? Is it not displayed? Is it not part of the document? Is it covered up by something else? etc. etc.
As a rule of thumb though, you should avoid intrinsic event attributes in favour of assigning event handlers via JavaScript stored in external files. This is part of unobtrusive JavaScript.
You could change the code of Brian Driscoll to make it dynamic like so:
<html>
<head>
<script language="javascript" type="text/javascript">
function imageSwap(el) {
var img = el.id;
//swap out the image...
}
</script>
</head>
<body>
<?php echo "<img id='img1' onmouseover='imageSwap(this)' src='img/img.png'>" ?>
</body>
</html>
This way you will always have the correct id from the image your are hovering on. No matter the amount of images

Categories