How to include inline JS files with PHP? - javascript

Normally that is how one includes JS files in HTML:
<script type="text/javascript" src="myFile.js" ></script>
But I want to write the JS file inline the HTML, using PHP; but still having the possibility of having my neat JS file, that can be chached, debugged and minified.
How can I do something like this?
<script>
<?php include 'myFile.js';?>
</script>
In other words, how to include a JS file in HTML on the server-side. That may get a lot of advantages because it is transparent to the browser.

How can I do something like this?
<script>
<?php include 'myFile.js';?>
</script>
Exactly that code would work, yes. Though it would try to interpret the file as PHP code, and if anything looked like <?php .. ?> inside that file you may see weird side effects. If you want to include the file uninterpreted, simply do:
<script><?php echo file_get_contents('myFile.js'); ?></script>
Be aware of possibly having to escape "</script>" now, should that appear in your included file; see https://stackoverflow.com/a/6908901/476.

YOu need to make custom function or use :
echo '<script type="text/javascript" src="myFile.js" ></script>';
Or
function add_js($filename){
return '<script type="text/javascript" src="'.$filename.'" ></script>';
}
echo add_js('myFile.js');

Related

Substituting PHP into JavaScript

I notice that I can substitue PHP into JavaScript that's place inline in the HTML, as below:
<script>
jQuery('select#age_group').val(<?php echo $age_group?>);
</script>
But the PHP substitution doesn't work inside a .js file that the PHP file loads. Why is that and how can I do the substituion in the loaded .js file?
Here are two ways you can do this without changing the file extensions that the PHP engine can process.
First, you can set a global variable inline and then access that variable in the JS you include.
<script>global_age_group = <?php echo $age_group?>;</script>
<script src="js_that_accesses_age_group.js" /></script>
(standard warnings about global variables apply)
Second, you can give your JS file a .php extension, so...
<script src="js_that_accesses_age_group.php" type ='application/javascript'/></script>
And then use
<?php echo $age_group?>
in that file as you do in your inline example.
Try this instead... Let me know if it works
</form>
</div>
<?php echo"<script>
jQuery('select#age_group').val($age_group);
</script>";
?>
</body>
</html>
you pass the value on a element attribute or on js var as you did
<script>
var age = 20;
</script>
<script src="main.js"></script>
and your can use the age inside main.js
By default, PHP will only process files ending in certain extensions (most commonly .php). If you want to use PHP in a JavaScript file then the easiest way to do it is to give it a .php extension.
Most browsers will also refuse to process your JavaScript unless it has the right content type, so at the top of your file add
<?php
header("Content-Type: application/javascript");
The Simple answer that you can't !
You can't write a PHP script any where except .php files,
That you can't write php scripts in .html, .css or .js files because the compiler will not pass .js file or .html file to read it!

display php file content in the javascript of another php file

So basically i want to html() a php file but i seem to fail, maybe it isn't possible but i want to make sure.
This is an example code (not the real one):
page.php:
<? //some code generating html ?>
<div class='content'></div>
<script type='text/javascript'>
$('.content').html("<? include('php/content.php'); ?>");
</script>
php/content.php:
<div class='realContent'>Awesome Stuff Here</div>
Note: I know there is .load(), $.post and many others. I just want to know if this practic is possible, .html()-ing a php file's contents.
Thank you in advance, awesome community!
d3nm4k.
The code in my example does what you want.
Maybe you got the problem with the short opening tags that is < ? ? >.
The file I'm trying to load in my example is located in app/View/Tests/def.php and works just fine.
Hope it helped you!
<div class='content'></div>
<?php
$fileLocation = APP . 'View/Tests/def.php';
// Ensure the file exists
echo "FILE EXISTS: <b>" . (file_exists($fileLocation) ? "TRUE" : "FALSE") . "</b><br /><br />";
?>
<?php
// Alternatively, you can try this one
//include $fileLocation;
?>
<script type='text/javascript'>
$('.content').html("<?php include($fileLocation); ?>");
</script>
You can do it, the code you gave i tried it just by adding ?php
<div class='content'></div>
<script type='text/javascript'>
$('.content').html("<?php include('php/content.php'); ?>");
</script>
When the php is executed on server it replaces content with actual html inside html() function. And on client side javascript plays its role to render it.

jquery script tag visible in each page

I have included this code using php "include" at the end of the body tag in
</div>
<?php include "jq.php" ?>
</body>
</html>
contents of jq.php----------------------------------------------------------------------------------
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
if (!window.jQuery)
{
document.write('<script src="./script/jquery.min.js"><\/script>');
}
</script>
-----------------but it is visible at the end of each page----------------------------
There's still not much to go on why this isn't working without looking at a lot more of your codebase.
I'd suggest a few things. Firstly, that you probably don't need to include a local copy unless you're doing development work - the chances of Google's CDN being down are very low, and if the user can't access it you'll likely have trouble with other components of the page anyway.
If you do need the local version for development (e.g. if you want to test the site when you're offline) then simply add this to PHP:
if (is_development()){
echo '<script src="./script/jquery.min.js"></script>';
}
else {
echo '<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>';
}
Where is_development() checks some defined CONSTANT or (less ideally) a global variable or local file.
The final approach would be to simply include the jQuery code at the top of your own JS file:
if (!window.jQuery){
var jQuery=.... // full minified jQuery here
}
None of those really answer your query but they should help you continue with your development without too many more problems relating to this issue.

a javascript function called by javascript echoed by php doesn't response

I executed 2 javascript function, echoed by php code, in different ways. here is code.
<head>
<script>
aJavascriptFunction(){
document.write( 'php echo writted javascript to call another javascript function ,outside php echo, that write this html' );
}
</script>
</head>
<html>
<head>
</head>
<body>
<?php
echo "<script>document.write('php echo writted javascript to write this html')</script>"; //first case
echo "<br>";
echo "<script>aJavascriptFunction();</script>"; //second case
?>
</body>
</html>
first case, echoed javascript code that directly make function, works well. but second case that echoed javascript code that call another javascript function outside php echo doesn't work.
Could anyone explain why first case works well, but second case doesn't work?
I'm making php file that contain html, javascript and php code inside 'a' file index.php. I want to write html code basically by php echo function. What I'm trying to do is defining javascript functions, php functions separately to call from anywhere in html code(in same file) written by php echo function. I think that separating javascript and php code by separate file will be ultimate answer to my project. but for now, I'm not completely understanding how javascript and php code works in client and server. so, I need to complete my project using style above and remain understanding for latter.
Your code is kinda messy so it is hard to work with. But I will tell you this:
Syntax Error on line 14, unexpected <
It is an issue with your quotes and semicolons.
You have messed up your code.
<html>
<head>
<!-- Your script has to be inside head or body -->
<script type="text/javascript">
// Here is a valid javascript function
function myTestFunction(){
// Print inside browser console
console.log('I was executed.');
// Anyway if need to write
document.write('I was executed.');
}
</script>
</head>
<body>
<?php
echo '<script type="text/javascript">myTestFunction();</script>';
?>
</body>
</html>

Is it possible to put a javascript function in a php file?

Non-programmer here, trying to figure something out.
I have a javascript function in the header of my document that upon page load it opens another page in an iframe and reveals an svg file on my server for minor online editing. I would like to place my javascript function in a php file, so that these folder locations of the svg files cannot be determined for anyone to download these svg files freely.
Currently I have this on my html header:
<script type="text/javascript">
function loaded()
{
document.getElementById("myiframe").src="http://www.mydomain.com/myfolder/mypage.html?url=myotherfolder/"+window.location.search.substr(1);
}
onload=loaded;
</script>
Since I have heard that php is a server side script and not viewable, I thought this would mask the location of these files on my server.
I want to remove this javascript code from my header and place it in a php file and replace the header code with either of these:
<script src="phpjavafile.php"></script>
or
<?php include ('phpjavafile.php'; ?>
and finally put the javascript into a php file like this:
<?php
<script type="text/javascript">
function loaded()
{
document.getElementById("myiframe").src="http://www.mydomain.com/myfolder/mypage.html?url=myotherfolder/"+window.location.search.substr(1);
}
onload=loaded;
</script>
?>
I have tried both of these methods and neither load properly.
I must be doing something wrong. Am I on the right track, or is there a better way of getting this to work.
Thank you ahead of time.
By using the echo() function
PHP
<?php
echo '<script>
some javascript
</script';
?>
However if you are just trying to load the php on page load without any php args then just write it out of the tags.
If you have the JavaScript is another file then using
PHP
<?php
include 'path/to/javascript/file.php';
?>
Should work.
You cannot hide javascript as it is interpreted browser side and not server side so the users browser has to have accesses to the code.
Here is the code I think you are asking for:
PHP HTML
<?php
$html = file_get_contents("path/to/data.html");
?>
<div>
<?php echo $html; ?>
</div>
doesn't use an iframe but should still work. However any relative links will not work unless both files are in the same dir and there will be no iframe functionality without additional css
You can just output it as text in your PHP file.
<?php
// Some PHP stuff here
?>
<script type="text/javascript">
function loaded(){
....
}
onload=loaded;
</script>
<?php
// Some more PHP stuff here
?>
Alternatively, you can just link to it in the usual way from within the same file:
<script src="path/to/your/file.js"></script>

Categories

Resources